⬆️ ⬇️

Vkontakte presented SDK for Android

VKontakte submitted SDK for Android

The other day VKontakte in the section for developers posted the SDK for Android.





The popular social network VKontakte has expanded its application development toolkit, which already has Flash and Javascript SDK, as well as an iOS SDK, and another for the Android SDK.



This library includes tools for authorization, both when there is an official client on the user's device and in its absence, as well as tools to facilitate the compilation / execution of requests and processing responses.

')

The guys did not forget about the owners of devices with irrelevant Android versions on board - the test application that comes with the SDK has Android 2.2+ requirements



Also not left without attention to the issue of protection.

Details under the cut.



Where to get?


VK Android SDK is available for download on GitHub .



How to connect?


SDK to the project


In Eclipse, which, by the way, I use, as well as in Android Studio, using the Gradle collector, the VK SDK is connected in the same way as any other library, so I will not dwell on it. I can only say that for convenience, I changed the folder structure:

Before => After



If you are not using Gradle in Android Studio, then you should rename the plug-in from “main” to “vksdk”.



In the manifest, you must register activity com.vk.sdk.VKOpenAuthActivity.



Project to VK


Application settings The developers have created a security system, due to which another application can not impersonate yours.





How to use?


Authorization


When you start the application, you need to initialize the SDK:

VKSdk.initialize(VKSdkListener listener, String appId, VKAccessToken token);



Authorization is recommended in one of the following ways:

VKSdk.authorize(String... scope);

VKSdk.authorize(String[] scope, boolean revoke, boolean forceOAuth);

By default, authorization occurs through the client's VKontakte. If the user’s device is not installed or forceOAuth == true, then the authorization page opens in a separate activity.



Since the library includes interface elements, it needs to keep track of what is happening on the display. To do this, use the class VKUIHelper. Therefore, in all activities, you need to override methods like this:

 @Override protected void onResume() { super.onResume(); VKUIHelper.onResume(this); } @Override protected void onDestroy() { super.onDestroy(); VKUIHelper.onDestroy(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { VKUIHelper.onActivityResult(requestCode, resultCode, data); } 


Sample activity:

 public class LoginActivity extends Activity { private static String sTokenKey = "VK_ACCESS_TOKEN"; private static String[] sMyScope = new String[]{VKScope.FRIENDS, VKScope.WALL, VKScope.PHOTOS, VKScope.NOHTTPS}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); VKSdk.initialize(sdkListener, "id_", VKAccessToken.tokenFromSharedPreferences(this, sTokenKey)); setContentView(R.layout.activity_login); VKSdk.authorize(sMyScope, true, false); } @Override protected void onResume() { super.onResume(); VKUIHelper.onResume(this); } @Override protected void onDestroy() { super.onDestroy(); VKUIHelper.onDestroy(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { VKUIHelper.onActivityResult(requestCode, resultCode, data); } private VKSdkListener sdkListener = new VKSdkListener() { @Override public void onCaptchaError(VKError captchaError) { new VKCaptchaDialog(captchaError).show(); } @Override public void onTokenExpired(VKAccessToken expiredToken) { VKSdk.authorize(sMyScope); } @Override public void onAccessDenied(VKError authorizationError) { new AlertDialog.Builder(LoginActivity.this) .setMessage(authorizationError.errorMessage) .show(); } @Override public void onReceiveNewToken(VKAccessToken newToken) { newToken.saveTokenToSharedPreferences(LoginActivity.this, sTokenKey); Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivity(i); } @Override public void onAcceptUserToken(VKAccessToken token) { Intent i = new Intent(LoginActivity.this, MainActivity.class); startActivity(i); } }; } 


Query execution


You can make a request using the model available in the SDK:

VKRequest request = VKApi.users().get();

Or directly specify the name of the called method:

VKRequest request = new VKRequest("status.get");

The same with the parameters:

VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.USER_IDS, "1,2"));

VKRequest request = new VKRequest("friends.get", VKParameters.from(VKApiConst.FIELDS, "sex,bdate,city"));



There are special request types for uploading photos - VKUploadAlbumPhotoRequest for uploading to an album and VKUploadWallPhotoRequest for uploading to a wall. Both have two constructors:

 VKRequest request = VKApi.uploadWallPhotoRequest(VKUploadImage image, int user_id, int group_id); VKRequest request = VKApi.uploadAlbumPhotoRequest(VKUploadImage image, int album_id, int group_id); VKRequest request = VKApi.uploadWallPhotoRequest(File image, int user_id, int group_id); VKRequest request = VKApi.uploadAlbumPhotoRequest(File image, int album_id, int group_id); 


When uploading a photo to our wall or the wall of the group user_id == 0, otherwise - the id of the user, on the wall of which we will take photos to shit .

When uploading photos to a wall / group album group_id == id of the target group, otherwise group_id == 0 (for example, uploading photos to your album).

In album_id, respectively, the ID of the photo album.



As for the VKUploadImage object, then in its constructor it is necessary to transfer the image as a Bitmap object and the VKImageParameters object representing the image type (png, jpg) and value of quality (for jpg).



Analogs for audio recordings, video recordings and documents have not yet been implemented, but I see no problems in doing this on my own. :-)



Before executing a query, you can change some of its parameters:

 //    .      API Error   . //  : 1.  0  infinity. request.attempts = 0; //    (HTTPS). //  false       scope (nohttps). //  : true. request.secure = false; //    ( ). //    false      -    . //  : true. useSystemLanguage = false; //  false        ,   SDK. //  : true. request.parseModel = false; 




The request is executed using the request.executeWithListener(VKRequestListener listener); method request.executeWithListener(VKRequestListener listener);

The server response (VKResponse) comes in the listener.

Sample request frame:

 request.executeWithListener(new VKRequestListener() { @Override public void onComplete(VKResponse response) { //    response. } @Override public void onError(VKError error) { // .    error. } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { //  .         . } }); 


You can run multiple queries in one batch. To do this, create, so to speak, a multi-request:

VKBatchRequest batch_req = new VKBatchRequest(VKRequest... requests);

As you can see, in one package there can be any number of requests.

A multi-request is performed as well as a single request, only with another listener:

 batch_req.executeWithListener(new VKBatchRequestListener() { @Override public void onComplete(VKResponse[] responses) { //   responses (    ,     ) } @Override public void onError(VKError error) { // .    error. } }); 


Processing responses


If an object is expected in the response, the Java representation of which is not yet in the SDK model, it makes sense to set parseModel = false; and independently process the received JSON. Otherwise, it is enough to bring the resulting object to the required type.



Conclusion


SDK Vkontakte for Android - quite a convenient and elegant tool. But, of course, still raw. File management is only a photo upload. Audio, video and documents while in the span. The model so far includes only user Java-views and photos. However, captcha processing tools and validation errors are already available.

The library has much to develop - and this means that you can participate in this and fit into the history of VKontakte.



You can read the official SDK for Android documentation here .



Thanks for attention.

Source: https://habr.com/ru/post/209974/



All Articles