Was this article helpful?

Android

Modified 15:52, 16 May 2013 by Tanya

The Android client library provides a Java interface for the Gigya API. The library makes it simple to integrate Gigya's service in your Android application. This document is a practical step-by-step guide for programmers who wish to integrate the Gigya service into their Android application. Follow the steps below to get started, and use the Library Reference while implementing.

Note: Android SDK requires Android 2.1 and above.

Note: If you wish to integrate the Gigya service in your server application, please refer to our Server Side SDKs and choose the SDK that suits your development platform. 

 

Download

Download the SDK JAR file:

If you are upgrading from a former version, please make sure to read the SDK's Change Log.

 

Library Guide

Please follow these steps to integrate Gigya's Android library:

  1. Download the SDK JAR file (above).
     
  2. Paste the following line in your app's AndroidManfiest.xml
    <activity android:name="com.gigya.socialize.android.GSWebViewActivity" />
    Modify the application manifest to allow the application to make network calls. Do this by adding the following to the AndroidManifest.xml file in the app project:
    <uses-permission android:name="android.permission.INTERNET">
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
    </uses-permission>

     

  3. Add the google-play-services.jar file as a dependency to your android project.
  4. Gigya Setup - obtain your Gigya API key
  5. Initialize - create an instance of class GSAPI
  6. Login the User
  7. Use Gigya's API - Send Requests

 

Gigya Setup - Obtain Your Gigya API Key

Go to the Site Dashboard page on Gigya's website. Follow the instructions in the Gigya's Setup guide to setup your application and obtain a Gigya API key.

Important: Please make sure to check the Enable Mobile or Desktop Client Applications API Access checkbox in the Permissions page.

 

Initialization - Create an Instance of the GSAPI Class

Class GSAPI is the central class of the Gigya Android API. Instances of the GSAPI class provide access to the Gigya service.
As a first step for using Gigya service, create a new instance of GSAPI:

GSAPI gsAPI = new GSAPI("PUT-YOUR-APIKEY-HERE", this);

 

Class GSAPI has one constructor:

public GSAPI(java.lang.String apiKey, android.app.Activity parent)

Parameters:

  • apiKey - your Gigya API key, which you have obtained in the previous step.
  • parent - the Android activity.

You should create only one GSAPI object and retain it for the lifetime of your application.
 

Logging in the User

The first interaction with Gigya must always be logging in. If the user is not logged in, you cannot access her social profile nor perform social activities, such as setting her status. The quickest way to implement logging-in is using the showLoginUI method of class GSAPI. The method opens a login user interface, which presents a selection of providers' icons, enabling the user to login via his social network / webmail account. Here is a screenshot of the Login UI:

Android-LoginUI.gif

 

The following code displays the Login UI (with default preferences):

// Present the Login user interface.
gsAPI.showLoginUI(null, null, null);

 

Note: If you wish to implement the graphic design by yourself, use the login method instead.

The following providers currently support the login operation: Facebook, Twitter, Yahoo, Microsoft Messenger, Google, Google+, LinkedIn, Myspace, AOL, FourSquare, Orkut, Renren, Tencent QQ, Sina Weibo, Kaixin, Vkontakte, WordPress, Blogger, Typepad, Paypal, liveJournal, Hyves, VeriSign, OpenID, Netlog, Signon, Orange France, mixi, Yahoo Japan, Spiceworks, Livedoor, Skyrock, VZnet.

 

Registering to the onLogin Event

After the user has been successfully logged in, Gigya fires an 'onLogin' event. You may register to the event, receive a notification from Gigya when the login process concludes, and apply post login operations (such as updating the UI). To implement this, you'll need to:

  1. Define a class that implements the GSLoginUIListener interface. In the onLogin method implementation, include actions that should follow successful login.
    // Defining a Login event listener
    class LoginUIListener implements GSLoginUIListener {
        public void onLogin(String provider, GSObject user, Object context) {
            String nickname = user.getString("nickname");
            Int age= user.getInt("age");
            System.out.println("The user logged in using " + provider + "\n" + "User name: " + nickname + "; The user's age: " + age);	
        }
    }
  2. When executing the showLoginUI method, pass an instance of your listener as the second parameter:
    // Present the Login user interface.
    // Register to login events (2nd parameter).
    gsAPI.showLoginUI(null, new LoginUIListener(), null);

 

Social Registration

Please refer to our Social Login guide, which provides a specification of Gigya's complete best-practice login/registration flows. Please note that the guide provides step-by-step implementation instructions using our JavaScript SDK. To implement you'll need to substitute the JavaScript methods with parallel iOS SDK methods (the highlight methods are the ones described above).

Site Credentials

If you wish to implement site login (using your own login form, and site credentials) along side with Gigya login, read below how to synchronize site login with Gigya Service.

 

Sending a Request

After you have logged in the user, you may use the GSAPI to access the user profile and perform various activities. This is implemented using GSAPI's sendRequest method. The following code sends a request to set the current user's status to "I feel great":

// Step 1 - Defining request parameters
GSObject params = new GSObject();
params.put("status", "I feel great");  // set the "status" parameter to "I feel great"

// Step 2 - Defining response listener. The response listener will handle the request's response.
GSResponseListener resListener = new GSResponseListener() {
        @Override
        public void onGSResponse(String method, GSResponse response, Object context) {
            try {
                if (response.getErrorCode()==0) { // SUCCESS! response status = OK
                    System.out.println("Success in setStatus operation.");                
                } else {  // Error
                    System.out.println("Got error on setStatus: " + response.getLog());
                }
            } catch (Exception ex) {  ex.printStackTrace();  }
        }
    };

// Step 3 - Sending the request
String methodName = "socialize.setStatus";
gsAPI.sendRequest(methodName, params, resListener, null);

 

Step 1: Define the Request Parameters

Create a GSObject instance and fill it with parameters. There are two ways to define the parameters:

1. Construct a GSObject from a JSON string. For example:

GSObject params = new GSObject("{param1:'value1', param2:'value2', param3:'value3',...}");

2. Construct an empty GSObject and add parameters using the put method:

GSObject params = new GSObject();
params.put("param1", "value1"); 
params.put("param2", "value2"); 
params.put("param3", "value3"); 
...

When a parameter is a complex object, you can use compound GSObjects or a JSON string as the value. See the example below.

Note: You can find the list of available Gigya API methods and the list of parameters per each method in the REST API reference

 

Step 2: Define the Response Listener

To define a response listener, define a class that implements the GSResponseListener interface. The onGSResponse method implementation should handle the response.

class MyResponseHandler implements GSResponseListener {
        @Override
        public void onGSResponse(String method, GSResponse response, Object context) {
                 // Handle response here...
        }
}

 

The GSResponse object includes data fields. For each request method the response data fields are different. Please refer to the Gigya REST API reference for the list of response data fields per method.
For example - handling a 'getUserInfo' response:
The response of 'getUserInfo' includes a 'user' object.

class UserInfoResponseHandler implements GSResponseListener {
        @Override
        public void onGSResponse(String method, GSResponse response, Object context) {
                // Handle response here...
		try {
			if (response.getErrorCode()==0) {  // SUCCESS! response status = OK
                                String nickname = response.getString("nickname",""); // Second parameter gets default value
                                String age= response.getInt("age");
                                alert("User name: " + nickname + "; The user's age: " + age);	
			} else {
				alert("Got error on getUserInfo: "+response.getLog());
			}
		} catch (Exception ex) {  ex.printStackTrace();  }
        }
}

  

Step 3: Sending the Request

Execute the sendRequest method:

gsAPI.sendRequest("socialize.setStatus", params, resListener, null);

The parameters of the method are:

  1. method - the Gigya API method name. Please refer to the REST API reference for the list of available methods.
  2. params - the parameters object that you have created in Step 1.
  3. listener - the response listener object that you have created in Step 2.
  4. context - an optional object that is passed back with the response.

 

Example - Publishing User Action

The following code sample sends a request to publish a user action to the newsfeed stream on all the connected providers that support this feature.
The socialize.publishUserAction method has a complex parameter called userAction, which defines the user action data to be published. To define the userAction parameter create a GSObject object and fill it with data. There are two ways to fill the GSObject with data; you can either use the put method or construct the GSObject with a JSON string, as shown in the two examples below:
 

Option A - Using GSObject's put Method

// 1. Defining request parameters
GSObject userAction = new GSObject();

userAction.put("title", "This is my title");
userAction.put("userMessage", "This is my user message");
userAction.put("description", "This is my description");
userAction.put("linkBack", "http://google.com");
			
GSArray mediaItems = new GSArray();
mediaItems.add(new GSObject("{\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}"));
userAction.put("mediaItems", mediaItems);

GSObject params = new GSObject();
params.put("userAction", userAction); // set the "userAction" parameter 

// 2. Sending 'socialize.publishUserAction' request
gsAPI.sendRequest("socialize.publishUserAction", params, null, null);

 

Option B - Using a JSON String

// Defining the userAction parameter 
GSObject userAction = new GSObject("{\"title\":\"This is my title\", \"userMessage\":\"This is a user message\", 
     \"description\":\"This is a description\", \"linkBack\":\"http://google.com\", 
     \"mediaItems\":[ {\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}]}"); 

GSObject params = new GSObject();
params.put("userAction", userAction);  // set the "userAction" parameter 

// 2. Sending 'socialize.publishUserAction' request 
gsAPI.sendRequest("socialize.publishUserAction", params, null, null);

 

To learn more about publishing user actions, please read the Advanced Sharing guide.

 

Advanced Topics

Site Login - Synchronizing with Gigya Service

When a user authenticates using your existing login form or when a new user registers using site registration, it is important to notify Gigya of the user's new state, so as to provide consistent user experience and have access to Gigya's API. The following chart diagram illustrates the implementation:

Mobile_siteLogin.gif

 

  • Steps 1-3: your standard site login/registration flow.
  • Step 4: call the socialize.notifyLogin API method. Pass the following parameters:
    • siteUID - set this parameter with the user ID that you have designated for this user in your database. The notifyLogin call registers a new user in Gigya in case the siteUID provided is new, or reconnects a returning user in case the siteUID already exists in our records.
    • newUser - If it is a new user set the newUser parameter to 'true'. This will enable Gigya to distinguish between a new site user and a returning site user, allowing Gigya to analyze users' login/registration behavior with or without Social Login and compare the ratio.
  • Step 5: the notifyLogin response data includes the following fields: sessionToken and sessionSecret.
    The following code is the implementation of steps 4,5 using Gigya's Java SDK:
    // Define the API-Key and Secret key (the keys can be obtained from your site setup page on Gigya's website).
    final String apiKey = "PUT-YOUR-APIKEY-HERE";
    final String secretKey = "PUT-YOUR-SECRET-KEY-HERE";
    
    // Defining socialize.notifyLogin request 
    String methodName = "socialize.notifyLogin";
    GSRequest request = new GSRequest(apiKey, secretKey, method);
    request.put("siteUID", "12345");  // The ID you have designated to this user
    request.put("targetEnv", "mobile");
    request.put("newUser", true);  // whether or not this user is new (registration vs login)
    
    GSResponse response = request.send();
    
    if (response.getErrorCode() == 0)
    { 
        String sessionToken = response.getString("sessionToken");
        String sessionSecret = response.getString("sessionSecret");
        /* send the sessionToken & sessionSecret to the client app
        ...
        */
    }
    else {
        System.out.println("Got error on notifyLogin: " + response.getLog());
    }
  • Step 6: pass the sessionToken and sessionSecret to your client app.
  • Step 7: create a session on your client app using the sessionToken and sessionSecret fields, so as to maintain the client application synchronized with the user state. Use the GSAPI.setSession(GSSession session) method:
    // Create and store a session
    String sessionToken; // value received from server
    String sessionSecret; // value received from server
    long expirationSeconds = 6 * 60 * 60; // The session will expire 6 hours from now (setting expiration time is optional)
    GSSession session = new GSSession(sessionToken, sessionSecret, expirationSeconds);
    gsAPI.setSession(session);  // Store the session in the app's storage

     

  • Step 8: As long as the session is valid (not expired and has valid token), the client app will have access to Gigya's API.

 

 

Adding Facebook Single Sign-on

Single sign-on is an improvement to the way your users currently log into their mobile applications on Facebook. By providing their Facebook username and password information just once, your users will now have one-click login access to all participating platform applications on their mobile phone. 

Note: If you want certain permissions, you must ask for them explicitly, using Facebook's permission strings as defined in Facebook's documentation.

Follow these steps to implement single sign-on for Android:

  1. Export the signature for your app so that Facebook can use it to ensure users are only communicating with your app on the Android. This is done by running the keytool. The following shows how to export the key for your app using the debug defaults specified by the Android SDK and Eclipse:
    keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore 
    | openssl sha1 -binary
    | openssl base64

    Note: Due to an unresolved external bug, this cannot be generated in Windows.

    This tool generates a string that must be registered in the Mobile & Devices section of the Developer App for your app:
    Capture.PNG

    Insert the string that was created as a result of running the keytool.
    For more information, please refer to Facebook's documentation at http://developers.facebook.com/docs/guides/mobile/#android.
     
  2. Your App Settings page displays a Facebook parameter called App ID:
    fb_settings_2.PNG

    Pass the Facebook App ID when calling showLoginUI, login, showConnectUI, or connect as follows:
    GSObject params = new GSObject();
    params.put("facebookAppId", YOUR_FB_APP_ID );
    api.showLoginUI(params, new LoginUIListener(), null);

 

Using Google+ Native Android Sign-on

Android enables users to set their Google account on their device. Android applications can access the native account to authenticate the user without requiring the user to enter their credentials. We recommend utilizing this functionality on your Android app.
Note: Google+ native sign-on will work on devices that have "Google Play Services" application installed. Gigya will fallback to webview in devices that don't have the application installed.

Follow these steps to utilize Google+ native Android sign-on:

  1. Add the following lines to the AndroidManifest.xml file in your app's project:
    <uses-permission android:name="android.permission.GET_ACCOUNTS">
    </<uses-permission>
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS">
    </<uses-permission>
    <uses-permission android:name="android.permission.USE_CREDENTIALS">
    </<uses-permission>
  2. Follow Google's instructions that are specified in Step 1: Enable the Google+ API (only Step 1 is required).
     
  3. Please make sure you have set up a web application in Google+ as part of the Gigya Setup process. Gigya will use the web application as a fallback in devices that don't have "Google Play Services" application installed.

 

 

Verifying Signatures from Mobile Logins

The process for verifying UID signatures generated from logins via our mobile SDKs depends on whether your API key begins with 2_xxx (older) or 3_xxx (newer).

For API keys beginning with 2_xxx the process is as follows:

  1. Upon user login, grab the "accessToken" and "secret" from the getSession method of GSSession in your mobile SDK.
  2. Over HTTPS, pass this accessToken and secret to your application server.
  3. Call getUserInfo (without specifying a UID) passing the accessToken and secret as the API Key and Secret Key (respectively) to the Gigya API.
  4. Assuming the accessToken and secret that you received in iOS is valid, you will receive a valid response from the getUserInfo call.


For API keys beginning with 3_xxx the process is as follows:

  1. Upon user login, grab the UID, Signature, and Timestamp from the response and pass it to your application server.
  2. Use your SDK's SigUtils.validateUserSignature() method, passing in the data you received from step 1 and your Gigya secret key.
Was this article helpful?
Pages that link here
Page statistics
8644 view(s) and 20 edit(s)
Social share
Share this page?

Tags

This page has no custom tags set.

Comments

You must to post a comment.

Attachments