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".
To receive your certificate's fingerprint you can use one of the following methods.
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.
2) After the keystore's location has been found, use keytool utilite (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.
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, fingerprint contains a single line. It's a fingerprint of your certificate (depends on the certificate used for your app's signing)
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.
You can add next maven dependency in your project:
You may also need to add the following to your
project/build.gradle file.
implementation 'com.vk:androidsdk:2.2.3
For example, your
app/build.gradle script will contains such dependencies:
dependencies {
implementation 'com.vk:androidsdk:2.2.3
}
Older version of sdk can be found
here
1) Add permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
2) Add this to the resource file (example strings.xml):
<integer name="com_vk_sdk_AppId">your_app_id</integer>
Use VK.login method:
VK.login(activity, arrayListOf(VKScope.WALL, VKScope.PHOTOS))
Override onActivityResult:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val callback = object: VKAuthCallback {
override fun onLogin(token: VKAccessToken) {
// User passed authorization
}
override fun onLoginFailed(errorCode: Int) {
// User didn't pass authorization
}
}
if (data == null || !VK.onActivityResult(requestCode, resultCode, data, callback)) {
super.onActivityResult(requestCode, resultCode, data)
}
}
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
}
}
}
1) Override VKRequest. For example:
VKUsersRequest class VKUsersRequest: VKRequest<List<VKUser>> {
constructor(uids: IntArray = intArrayOf()): super("users.get") {
if (uids.isNotEmpty()) {
addParam("user_ids", uids.joinToString(","))
}
addParam("fields", "photo_200")
}
override fun parse(r: JSONObject): List<VKUser> {
val users = r.getJSONArray("response")
val result = ArrayList<VKUser>()
for (i in 0 until users.length()) {
result.add(VKUser.parse(users.getJSONObject(i)))
}
return result
}
}
2) Run request with VK.execute:
VK.execute(VKUsersRequest(), object: VKApiCallback<List<VKUser>> {
override fun success(result: List<VKUser>) {
}
override fun fail(error: VKApiExecutionException) {
}
})
3) 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
})
4) 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 : VKApiResponseParser<List<VKUser>> {
override fun parse(response: String): List<VKUser> {
try {
val ja = JSONObject(response).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.