Mobile Zone is brought to you in partnership with:

German has posted 19 posts at DZone. View Full User Profile

Adding Facebook Authentication to Your Android Application

05.03.2013
| 14194 views |
  • submit to reddit

Social login is not only a buzz. An increasing amount of research confirm the benefits of providing your users with the ability to login using social networks as an alternative to filling out registration forms. A recent study revealed, for example, that three out of every four Internet users leave a website rather than take the trouble to register a new account. The situation is no different with apps and it's even more critical since a mobile user on the go with an on-screen keyboard is less likely to fill-in a form than someone browsing the web.

No matter where your app user comes from, offering the option of signing in with a social login (e.g. Facebook or Twitter) as an alternative to filling out a form has several benefits:

  • Increase of user acquisition rates by making the signup process easier (one click signup/login)
  • Better data collection since you often get additional data together with social network user credentials/tokens (e.g. e-mail)
  • Improve social perception of your app
  • Increase in accuracy of user data (it's easier to fake data in a signup form than faking a full account in a social network)

Overall social login is a game changer and there's a strong trend of adoption across all mobile applications. But adding social login to your app is not for the faint of heart! Want to add a Twitter login to your app? There's no Android SDK. Maybe you can copy someone else's solution. Now you need to add a Facebook login? You can go check the Facebook Android SDK and follow the (not so) simple multiple steps to make it work.

Or you can just use Kii Cloud SDK. One consistent, robust and easy to use SDK that covers all you backend needs (from user management to full data management, from basic to fully customized analytics, from handling tons of ad networks with a few lines of code to doing push notifications in all its variants).

Here at Kii we work hard to make your life as an application developer easier. We want you to unleash the power of your app by focusing on making your app more awesome. We take care of the rest. That's why we created an easy to use social connector in our Kii Cloud SDK.

In this blog post I'm going to show you how to allow your users to signup/login to your Android app in a single step with just a few lines of code using the most popular social network: Facebook (which in Q1 2013 accounts for 46% of the social login preference).

Setting up Kii Cloud

First of all lets take a look at how to setup your Android app to use the Kii Cloud SDK. Go to developer.kii.com and sign-up. Once you log in click on "Create App", check the Android box, click on "Create", then click on the Android icon, scroll down a little bit and download the Kii Cloud Android SDK from the offered links (Cloud SDK v2.1.7). You'll get a jar file that you should include in a libs directory inside your Android Eclipse project and then, from Eclipse, you should "Add to Build path". Ok, we're now ready to work with Kii Cloud in your Android app.

The way in which Kii Cloud figures out which app you're working with is by using two tokens: the App Id and the App Key. Go to developer.kii.com, select the app you created in the previous step and click on "Access Keys" (look for the key icon). Write down the App Id and the App Key.

Now back to you Android project in Eclipse, add the following permissions to your AndroidManifest.xml:

     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

WRITE_EXTERNAL_STORAGE is only required if you are using the File Storage (KiiFile related) feature. If you're not you can just ignore it.

Before doing any API call you'll be required to initialize Kii Cloud with your app using the keys described above:

     Kii.initialize("APPID", "APPKEY", Site.US); 

You can do it in the onCreate() method of your main activity for example (it's ok to call the initialization multiple times). If you're in Japan you should use Site.JP instead of Site.US.

Easy, right?

How Kii Cloud signup and login work

Kii Cloud provides full management of your app users covering common scenarios such as user registration, validation and login against the cloud. If you take a look at the Kii Balance sample application for Android you'll see that a user registration is handled like this:

     // call user registration API
     RegisterCallback callback = new RegisterCallback(dialog);
     KiiUser user = KiiUser.createWithUsername(username);
     user.register(callback, password); 

As you can see we just need to pass a username and a password captured from a dialog in order to create a user in Kii Cloud. There's a callback involved because this is a non-blocking asynchronous variant that continues immediately after the registration method call (in general we offer both blocking and non-blocking + callback versions in a wide array of Kii Cloud methods). The registration callback will dismiss the dialog after a successful registration and proceed to login.

The login process is very similar:

     // call user login API
     LoginCallback callback = new LoginCallback(dialog);
     KiiUser.logIn(callback, username, password); 

Except that we need to pass both the username and password to verify a match against the cloud. Once the login is successful we can store the access token to automate the login process next time the user opens the app:

     // store access token
     KiiUser user = KiiUser.getCurrentUser();
     String token = user.getAccessToken();
     Preferences.setStoredAccessToken(activity, token); 

If you store the login token as explained above the app will have to verify if the token exists in the app preferences and do a login using it:

     // login with token
     AutoLoginCallback callback = new AutoLoginCallback(this);
     KiiUser.loginWithToken(callback, token); 

(the method onLoginCompleted() in the callback will be called once the token is verified as valid and then you'll have access to an authenticated user).

The whole process is simple and straightforward only requiring Internet access in your app. But what if you want to add the ability to signup and login in one step using Facebook?

Adding Facebook to the signup/login mix

Kii Cloud makes it really easy to handle login scenarios with social networks. When it comes to Facebook you'll probably spend more time setting up the app on the Facebook developer site than adding the login Kii Cloud code in your app. So, first of all, let's set up the app on Facebook:  

  1. Go to https://developers.facebook.com/apps and click on "+ Create New App". Enter your app name and click on "Continue"
  2. Write down the App Id provided by Facebook for the app. You'll need it later.
  3. Check "Native Android App" in the form and enter the package name of your app, the Activity that you want Facebook to open after a successful login and the key hashes (for info on how to calculate the key hash see this page). Most importantly make sure to check "Facebook login" as enabled. Note: you might also want to disable "sandbox mode" when going live.

We're all set on the Facebook side, let's go and set up the app for Facebook integration on the Kii Developer console:

  1. Go to developer.kii.com and click on your app. Click on "Edit" and then "Settings" and put your Facebook App Id from step 2 above in the Facebook id field.
  2. Click on "Save"

That's it on the Kii Developer console. It's now time to do some coding. Here's a code snippet for doing a Facebook login (we call it login but it's a signup + login all wrapped together):

     KiiSocialConnect conn = Kii.socialConnect(SocialNetwork.FACEBOOK);
     facebook.initialize(Constants.FB_APP_ID, null, null);     
     conn.logIn(activity, null, new KiiSocialCallBack(){
         @Override
         public void onLoginCompleted(SocialNetwork network, KiiUser user, Exception e){
             if (e == null) {
                 // Success.
             } else {
                 // Failure. handle error.
             }
         }
     }); 

In the snippet above "activity" is the activity that is going to handle the Facebook login. The logIn() method is non-blocking so we need to use a callback.

Important: The "activity" *must* also implement the onActivityResult() method that should include code to finalize the Facebook authentication:

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       Kii.socialConnect(SocialNetwork.FACEBOOK).respondAuthOnActivityResult(
           requestCode,
           resultCode,
           data);
     } 

It's also possible to link existing users to their Facebook accounts and the process is almost identical to what you saw with the login (just make sure your user is authenticated via Kii before linking/unlinking the account).

As you can see with Kii Cloud you can offer a Facebook login in your app within minutes. And since we maintain the backend you won't have to deal with any change of service or update in the Facebook API. We'll make sure your application keeps running smoothly so you can focus on what matter to your users.

Stay tuned for our next Android post that will show how to add support for multiple ad providers to you app with just a few lines of code while staying in control of ad network management.

For more information check out the Social Integration section in our Android documentation. You can get up to speed with Kii Cloud following the Android Guide and the Android Quickstart pages.
Published at DZone with permission of its author, German Viscuso.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)