• Stars
    star
    458
  • Rank 95,591 (Top 2 %)
  • Language
    Kotlin
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Android library for working with VK API, authorization through VK app, using VK functions.

VK SDK for Android

Maven Central

Library for working with VK API, authorization through VK app, using VK functions. Minimal version of Android is 5.0

Prepare for Using VK SDK

To use VK SDK primarily you need to create a new VK application here by choosing the Standalone application type. Choose a title and confirm the action via SMS and you will be redirected to the application settings page. You will require your Application ID (referenced as API_ID in the documentation). Fill in the "Batch name for Android", "Main Activity for Android" and "Certificate fingerprint for Android".

Certificate Fingerprint Receiving

To receive your certificate's fingerprint you can use one of the following methods.

Fingerprint Receiving via Keytool

  1. You need to find the keystore location for your app. The ''debug'' store is usually located in these directories:
  • ~/.android/ for OS X and Linux,
  • C:\Documents and Settings<user>.android\ for Windows XP,
  • C:\Users<user>.android\ for Windows Vista, Windows 7 and Windows 8.

The keystore for the release version is usually created by a programmer, so you should create it or recall its location.

  1. After the keystore's location has been found, use keytool utility (it is supplied with the Java SDK). You can get keys list with the following command:
keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v
You will observe a similar result:
Certificate fingerprint: SHA1: DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09
By deleting all the colons you'll get your key's fingerprint.

Fingerprint Receiving via SDK

If you've already added SDK to your project, you can use the following function in each Activity of your app.

String[] fingerprints = VKUtils.getCertificateFingerprint(this, this.getPackageName());

As a rule, fingerprints contains a single line. It's a fingerprint of your certificate (depends on the certificate used for your app's signing)

Fingerprint Receiving via Android Studio

Click in right menu on Gradle tab (or double shift and type Gradle). Open your project root folder, then open Tasks and after android. Run signingReport task. Find your SHA1 fingerprint in Run tab output.

You can add more than one fingerprint in your app settings, e.g., debug and release fingerprints.

Connecting VK SDK to Your Android Application

Connecting With Maven

Core Release

You can add next maven dependency in your project:

The available library modules are listed below.

  • android-sdk-core: Core functionality (required).

  • android-sdk-api : Api generated models and methods.

  • androidsdk: deprecated copy version of the android-sdk-core(will be removed in future releases since 01.09.2021).

  • androidsdkapi : deprecated copy version of the android-sdk-api(will be removed in future releases since 01.09.2021).

For example, your app/build.gradle script will contains such dependencies:

dependencies {
    implementation 'com.vk:android-sdk-core:3.x.x'
    implementation 'com.vk:android-sdk-api:3.x.x' // generated models and api methods
}

Using SDK

SDK Initialization

  1. Add permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
  1. Add this to the resource file (example strings.xml):
<integer name="com_vk_sdk_AppId">your_app_id</integer>

User Authorization

Create authorization launcher:

val authLauncher = VK.login(activity) { result : VKAuthenticationResult ->
    when (result) {
        is VKAuthenticationResult.Success -> {
            // User passed authorization
        }
        is VKAuthenticationResult.Failed -> {
            // User didn't pass authorization
        }
    }
}

In appropriate place call a created launcher:

authLauncher.launch(arrayListOf(VKScope.WALL, VKScope.PHOTOS))

Handling token authorization

Create instance of VKTokenExpiredHandler:

class SampleApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        VK.addTokenExpiredHandler(tokenTracker)
    }

    private val tokenTracker = object: VKTokenExpiredHandler {
        override fun onTokenExpired() {
            // token expired
        }
    }
}

API Requests

Run request with VK.execute and auto generated methods(android-sdk-api dependency is required):

VK.execute(FriendsService().friendsGet(fields = fields), object: VKApiCallback<FriendsGetFieldsResponseDto> {
            override fun success(result: FriendsGetFieldsResponseDto) {
                // you stuff is here
            }
            override fun fail(error: Exception) {
                Log.e(TAG, error.toString())
            }
        })

If you are using RxJava in your project, you can do something like this:

Observable.fromCallable {
    VK.executeSync(VKUsersRequest())
}
    .subscribeOn(Schedulers.single())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({
        // response here
    }, {
        // throwable here
    })

If you need more complex request, you should override ApiCommand. This approach allows you to make multiple requests at once For example: VKUsersRequest

class VKUsersCommand(private val uids: IntArray = intArrayOf()): ApiCommand<List<VKUser>>() {
    override fun onExecute(manager: VKApiManager): List<VKUser> {

        if (uids.isEmpty()) {
            // if no uids, send user's data
            val call = VKMethodCall.Builder()
                    .method("users.get")
                    .args("fields", "photo_200")
                    .version(manager.config.version)
                    .build()
            return manager.execute(call, ResponseApiParser())
        } else {
            val result = ArrayList<VKUser>()
            val chunks = uids.toList().chunked(CHUNK_LIMIT)
            for (chunk in chunks) {
                val call = VKMethodCall.Builder()
                        .method("users.get")
                        .args("user_ids", chunk.joinToString(","))
                        .args("fields", "photo_200")
                        .version(manager.config.version)
                        .build()
                result.addAll(manager.execute(call, ResponseApiParser()))
            }
            return result
        }
    }

    companion object {
        const val CHUNK_LIMIT = 900
    }

    private class ResponseApiParser : VKApiJSONResponseParser<List<VKUser>> {
        override fun parse(responseJson: JSONObject): List<VKUser> {
            try {
                val ja = responseJson.getJSONArray("response")
                val r = ArrayList<VKUser>(ja.length())
                for (i in 0 until ja.length()) {
                    val user = VKUser.parse(ja.getJSONObject(i))
                    r.add(user)
                }
                return r
            } catch (ex: JSONException) {
                throw VKApiIllegalResponseException(ex)
            }
        }
    }
}

VKUsersCommand supports dividing by chunks for working with api limits. This is main difference between VKUsersRequest and VKUsersCommand

Also you can check up VKWallPostCommand. This an example of complex api request with file uploading

More Repositories

1

kphp

KPHP — a PHP compiler
C++
1,322
star
2

VKUI

VKUI – это набор React-компонентов, с помощью которых можно создавать интерфейсы, внешне неотличимые от наших iOS и Android приложений.
TypeScript
995
star
3

YouTokenToMe

Unsupervised text tokenizer focused on computational efficiency
C++
951
star
4

noverify

Pretty fast linter (code static analysis utility) for PHP
Go
667
star
5

vk-ios-sdk

iOS library for working with VK API, authorization through VK app, using VK functions
Objective-C
298
star
6

vk-java-sdk

Java library for working with VK API
Java
290
star
7

vk-api-schema

JSON Schema of VK API
Shell
206
star
8

statshouse

StatsHouse is a highly available, scalable, multitenant monitoring system
C
206
star
9

vk-php-sdk

PHP library for working with VK API
PHP
204
star
10

vkompose

Kotlin Compiler Plugins, an IDEA Plugin, and a Detekt Rule that will help to improve your experience with Jetpack Compose
Kotlin
190
star
11

kittenhouse

Go
185
star
12

lighthouse

Lightweight interface for ClickHouse
JavaScript
185
star
13

joy4

Golang audio/video library and streaming server
Go
180
star
14

nocolor

Validate the architecture of your PHP project based on the concept of function colors
Go
161
star
15

nginx-quic

C
151
star
16

KNet

Android network library with QUIC protocol supporting.
Kotlin
148
star
17

nocc

A distributed C++ compiler: like distcc, but faster
Go
142
star
18

bot-example-php

Пример бота для VK
PHP
134
star
19

icons

Набор SVG иконок, представленный в виде React компонентов.
JavaScript
124
star
20

vk-bridge

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web
TypeScript
70
star
21

php-parser

PHP parser written in Go
Go
69
star
22

modulite

A plugin for PHPStorm that brings modules to the PHP language
Kotlin
65
star
23

vk-qr

VK QR Code generator library
TypeScript
58
star
24

create-vk-mini-app

Create VK Apps with no build configuration.
TypeScript
53
star
25

vk-miniapps-deploy

NPM module for deploy VK Mini Apps on VK hosting
JavaScript
49
star
26

kphpstorm

A PhpStorm plugin that makes IDE understand KPHP specifics
Kotlin
41
star
27

vkui-tokens

TypeScript
39
star
28

fastXDM

fast library for cross-domain messaging
JavaScript
39
star
29

node-vk-call

Simple API wrapper for VK.com social network
JavaScript
35
star
30

elephize

Typescript to PHP translation tool
TypeScript
33
star
31

vk-streaming-api

Go
33
star
32

vk-mini-apps-api

The official package for quick and easy development of VK Mini Apps
TypeScript
28
star
33

vk-mini-apps-router

TypeScript
27
star
34

Appearance

JavaScript
26
star
35

vkid-android-sdk

Kotlin
25
star
36

vkjs

VK shared JS libs
TypeScript
23
star
37

vk-router

TypeScript
22
star
38

vk-windowsphone-sdk

VK SDK for Windows Phone
C#
22
star
39

admstorm

PhpStorm plugin aimed at simplifying tasks at the junction of the local repository and the repository on the dev server
Kotlin
20
star
40

vk-unity-sdk

C#
20
star
41

vk-tunnel-client

TypeScript
19
star
42

kive

Go
19
star
43

tl

C++
18
star
44

vkdata-sketchplugin

Sketch plugin for using data from your account at vk.com
JavaScript
17
star
45

vk-apps-launch-params

Пример работы с параметрами запуска
JavaScript
17
star
46

nginx-http-vkupload-module

C
16
star
47

kphp-polyfills

PHP implementations of functions supported by KPHP natively (a Composer package)
PHP
15
star
48

superappkit-android-demo

Kotlin
15
star
49

vkid-web-sdk

TypeScript
15
star
50

vk-mini-apps-examples

TypeScript
15
star
51

IOSDevice

A set of hacks and workarounds for iOS Safari & Co.
JavaScript
14
star
52

docker-emulator-android

Dockerfile
13
star
53

modulite-phpstan

Bring modules into PHP and PHPStan
PHP
13
star
54

vk-apps-tensorflow-example

VK apps + tensorflow-js demo app
JavaScript
12
star
55

api-schema-typescript-generator

TypeScript
11
star
56

vkid-ios-sdk

Swift
11
star
57

api-schema-typescript

TypeScript
10
star
58

VKSDK-iOS

Swift
10
star
59

Delegate

Python
10
star
60

engine-go

Common libraries for our go engines (microservices)
Go
10
star
61

vk-direct-games-example

JavaScript
10
star
62

vk-ios-urlprotocol-example

This is an example iOS app with custom URLProtocol
Swift
10
star
63

swc-plugin-css-modules

Rust
9
star
64

vk-bridge-mock

The VK Bridge mock library
TypeScript
9
star
65

ktest

Test and benchmark KPHP code
Go
9
star
66

vk-ads-retargeting-demo

Демонстрация JavaScript API ретаргетинга ВКонтакте
HTML
8
star
67

eslint-config

JavaScript
8
star
68

useWeb3

JavaScript
8
star
69

TL-Schema-idea-plugin

Plugin for JetBrains products for coloring TL Schema files
Java
8
star
70

vk-connect-promise

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web with events based on promises
JavaScript
8
star
71

torch_mobile

Torch7 for mobile devices
C
7
star
72

vkui-benchmarks

JavaScript
7
star
73

noverify-phpstorm

NoVerify plugin for PhpStorm
Kotlin
6
star
74

superappkit-ios

Ruby
6
star
75

swc-plugin-transform-remove-imports

Rust
6
star
76

VideoPlayer-iOS

Swift
6
star
77

statshouse-go

StatsHouse client library for Go
Go
6
star
78

create-vkui-app

JavaScript
6
star
79

m3u8

Parser and generator of M3U8-playlists for Apple HLS.
Go
5
star
80

nginx-statshouse-module

StatsHouse module for nginx
C
5
star
81

statshouse-cpp

StatsHouse client library for C++
C++
5
star
82

statshouse-php

StatsHouse client library for PHP and KPHP
PHP
5
star
83

stylelint-config

TypeScript
4
star
84

statshouse-java

Java
4
star
85

modulite-example-project

This example project contains some Modulite errors, detected by IDE, PHPStan, and KPHP
PHP
4
star
86

kphp-tools

A set of independent tools to work with KPHP compiled code
JavaScript
4
star
87

kphp-snippets

Libraries written in PHP aimed to be compiled with KPHP
PHP
4
star
88

vk-mini-apps-course-frontend

TypeScript
4
star
89

graph-cache

Easy way to build and maintain persistent dependency graph for any type of files/languges
JavaScript
4
star
90

gulp-portal

JavaScript
4
star
91

sprites

Module for generate SVG sprites and PNG fallback
JavaScript
4
star
92

swc-plugin-pre-paths

Rust
3
star
93

mask-assets

AngelScript
3
star
94

mini-apps-analytics

TypeScript
3
star
95

vk-apps-currency

JavaScript
3
star
96

eslint-plugin

JavaScript
3
star
97

vk-apps-qr

VK Apps + QR demo app
JavaScript
2
star
98

ktest-script

PHP
2
star
99

mvk-mini-apps-scroll-helper

JavaScript
2
star
100

prettier-config

JavaScript
2
star