Was this article helpful?

Android

Last modified 13:00, 14 Oct 2014

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.

For your assistance, we provide a simple demo project for Eclipse, which includes a basic Gigya SDK integration.

Note: Android SDK requires Android 2.3 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. 

 

Note: If you want to upgrade an app that was developed with a version earlier than 3.1.1, use the Upgrade Guide to migrate your code.

 

Download

Download the SDK zip 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 zip file (above).
  2. Add to AndroidManfiest.xml
  3. Gigya Setup - obtain your Gigya API key
  4. Initialization
  5. Logging in the User
  6. Use Gigya's API - Send Requests

 

Add to AndroidManifest.xml

Paste the following lines in your app's AndroidManifest.xml, and make sure you replace "YOUR-PACKAGE-NAME" with the package of your MainActivity​:

<activity
    android:name="com.gigya.socialize.android.ui.HostActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<activity
    android:name="com.gigya.socialize.android.login.providers.WebLoginActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:launchMode="singleTask"
    android:allowTaskReparenting="true" >
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="YOUR-PACKAGE-NAME" android:host="gsapi" />
    </intent-filter>
</activity>

 

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>

 

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

The GSAPI class is the central class of the Gigya Android SDK. GSAPI is a singleton class that provides access to the Gigya SDK services.
As a first step for using Gigya service, insert the following code in your MainActivity's onCreate method:

GSAPI.getInstance().initialize(this, "YOUR-API-KEY");

 

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 account. Here is a screenshot of the Login UI:

Note: In order to use Facebook login you must add Facebook native login to your app. For more information go to the Facebook native login section.

android_login.gif

 

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

// Present the Login user interface.
GSAPI.getInstance().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, AOL, FourSquare, Instagram, Renren, Tencent QQ, Sina Weibo, Kaixin, Vkontakte, WordPress, Blogger, Typepad, Paypal, Amazon, liveJournal, VeriSign, OpenID, Netlog, Signon, Orange France, mixi, Yahoo JAPAN, Odnoklassniki, Spiceworks, Livedoor, Skyrock, VZnet, Xing.

Facebook require their app to have an Android definitions section.  For more information see Facebook Setup - adding the Android platform.

 

Registering for Gigya Global Events

The Gigya SDK provides two global event listeners that handle session changes, based on whether you are using Gigya's Social Login package (GSSocializeEventListener) or Registration-as-a-Service package (GSAccountsEventListener).

For example, using GSSocializeEventListener:

GSAPI.getInstance().setSocializeEventListener(new GSSocializeEventListener() {
    @Override
    public void onLogin(String provider, GSObject user, Object context) {
        // User was logged in
    }
    @Override
    public void onLogout(Object context) {
        // User was logged out
    }
    @Override
    public void onConnectionAdded(String provider, GSObject user, Object context) {
        // Social connection has been added to the user
    }
    @Override
    public void onConnectionRemoved(String provider, Object context) {
        // Social connection was removed from the user
    }
});

 

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.getInstance().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.getInstance().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.getInstance().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.getInstance().sendRequest("socialize.publishUserAction", params, null, null);

 

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

 

Configuring Native Login

Adding Facebook Native Login

Adding Facebook native login to your Android app is mandatory if you want to login via Facebook. Please follow the first 3 steps of Facebook's instructions on Facebook SDK for Android (1. Install the prerequisites, 2. Install the Facebook SDK for Android and the Facebook APK, 3. Import the SDK into Eclipse). Also open and configure a Facebook application (step 5 in Facebook SDK for Android).

If you want to ask the user for additional permissions, you need to use the GSAPI class requestNewFacebookPublishPermissions or requestNewFacebookReadPermissions methods

 

Adding Google+ Native Login

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.

Adding Google+ native login to your Android device is optional, and if you choose to add it, please follow the first 3 steps of Google's instructions at Google+ platform for Android (1. Enable the Google+ API, 2. Configure your Eclipse project, 3. Declare permissions).

 

Google+ Cross Platform SSO

Gigya's Android SDK supports Google+ cross platform SSO.  To see Google+ documentation click here.

If a user opens your Google+ application under Android, while the same user is logged in to that application on another platform, Gigya will identify that the user is already logged in and grant them access.

To implement this, call GSAPI's login method with the silent parameter set to true. The SDK will attempt to login the user without displaying any user interface, and invoke the response listener upon success:

GSObject params = new GSObject();
params.put("provider", "googleplus");
GSAPI.getInstance().login(params, new GSResponseListener() {
    @Override
    public void onGSResponse(String method, GSResponse response, Object context) {
         // Handle silent login
    }
}, true, null);
 

Integrating Your Site with the Android SDK

GSWebBridge connects between the Gigya JavaScript SDK and the Gigya Android SDK. Any WebView can be attached to the web bridge. Doing this provides the following benefits:

  • Session state will be synchronized. If the user is logged in and the session is active in the Android SDK - he will be automatically logged in in the JS SDK.
  • Any API requests by the JS SDK will be routed through the Android SDK, using the Android SDK session.
  • Any login process invoked by the JS SDK will be handled by the Android SDK, creating a seamless login experience - using the web browser or the provider's native login.

 

To register a web view, follow these steps:

  1. Call the attach method before the web view has started loading:
    GSWebBridge.attach(webView, new GSWebBridgeListener() { ... });
  2. Add the following code to the beginning of your WebViewClient implementation's shouldOverrideUrlLoading method:
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
          if (GSWebBridge.handleUrl(webView, url)) {
              return true;
          }
      }
  3. Detach the web view when finished:
    GSWebBridge.detach(webView);

 

Using Gigya Plugins in the Android SDK

GSPluginFragment is a custom fragment that renders Gigya JS Plugins and integrates them seamlessly with the Gigya Android SDK.

GSPluginFragment currently supports the following plugins, listed with their plugin name:

  • Comments - comments.commentsUI. Note: commenting is supported, but sharing the comment to social networks is not supported. 
  • Reviews - comments.commentsUI.
  • RaaS Screen-Sets - accounts.screenSet.
  • Share Bar - socialize.ShareBarUI. Please note: the share buttons that implement providers' own (native) buttons are not supported. These include Facebook's native Facebook Like button, Twitter's Tweet button, and more. For the full list please refer to the shareButtons parameter in socialize.showShareBarUI​.

You can either use showPluginDialog to display GSPluginFragment modally, or alternatively, for more control and customization, you can create an instance yourself and add it to your layout.

An example for using showPluginDialog to display GSPluginFragment modally:

GSObject params = new GSObject();
params.put("categoryID", "comments1");
params.put("streamID", "1");
params.put("captionText", "My Comments");
GSAPI.getInstance().showPluginDialog("comments.commentsUI", params, null, null);

 

An example for creating an instance yourself:

GSObject params = new GSObject();
params.put("categoryID", "comments1");
params.put("streamID", "1");
GSPluginFragment pluginFragment = GSPluginFragment.newInstance("comments.commentsUI", params);
getSupportFragmentManager().beginTransaction().add(R.id.my_layout, pluginFragment, "comments").commit();

         

You can also handle plugin events (for example, commentSubmitted) by implementing the GSPluginListener interface and passing it as a parameter.

For more information see reportDeepLink in the reference 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.


Checking the Session Status

As user sessions can expire from various reasons (like a timeout), and Gigya's API is only available through a valid session, it is recommended to perform validity checks before calling API methods on an uncertain session status.
The following code validates the current session:

//Stores the session data in a GSSession object
GSSession session = GSAPI.getInstance().getSession();
//Make sure session != null before validating
if (session != null && session.isValid()) {
   // User is logged in!
}

A call to GSAPI's getSession() method returns a GSSession Object that holds data for the current session. Calling getSession() on an invalid session may return a null value, so you should check that the session object is not null before calling the isValid() function.​ If the session is valid and the user is logged in isValid() will return true. Otherwise the return value is false. 

 

Tracking Deep Link Referrals

The Android SDK can be integrated with Gigya's Referred Traffic (link) report. Add the following code when your app is opened via deep link:
GSAPI.getInstance().reportDeepLink(intent);
 
For more information, see the reference (link to the reportDeepLink method in the GSAPI reference page).
 

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.

 

Eclipse Demo Project

We have created for your assistance a simple Eclipse project that integrates Gigya's Android SDK, with basic usage.

Download the Gigya Demo Project.

About the Demo

The demo project is a simple application, which implements Gigya's login, logout and retrieves the user's friends list.

Was this article helpful?
Pages that link here
Page statistics
812 view(s) and 7 edit(s)
Social share
Share this page?

Tags

This page has no custom tags.
This page has no classifications.

Comments

You must to post a comment.

Attachments