16 March 2016

Android social media - login with Facebook


I recently thought I’d try and add Facebook and Twitter login to an Android app I was creating. This is never as straightforward as it sounds as you've got to fully integrate with each parties SDK and link your app to their systems. First I'm going to tackle Facebook.


Facebook


Let’s try and add a Login With Facebook button to an app.


1) Sign Up as a Developer

First you need to sign-up on Facebook as a developer. You’ll need an existing Facebook account, but once you've done that you just sign up as a developer here:


2) Create an app.

This is your Facebook SDK “app” (not your Android app). This allows you to link your Android app with Facebook. It also allows Facebook to monitor your app and provide you with usage statistics. To get going go to this page and follow the steps.

3) Create your Android app 

Now we change to Android studio, create a new app, or open your existing app, whichever works for you. We need to tweak this app a little:
  • Add Maven Central to your gradle file
  • Add a dependency on Facebook SDK
  • Add a string to your strings file with your facebook_app_id
  • Add Facebook meta data to your manifest
  • Don’t forget to make sure you have Internet permissions
To be honest the Facebook quick start guide explains all the above really well with copy and paste code. Just use their example.

4) Configure your Facebook App

Now you need to configure the Facebook App to match your Android app. 
This involves finding your key hash. This is a bit complicated and can be quite confusing. The easiest way I know to do this is follow instructions on this Stack Overflow answer:
This means you don’t have to download, install and configure open ssl and other such tools, which is a relief. 

That’s it, if all this works you should be setup to start using Facebook login on your app. All that’s left now is to add the Android client code.


Android


Now we can add code to our Android app to show a Facebook Login button and to respond to Facebook login events. Thankfully this is relatively simple compared to the above.

1) Add an Application class

Create a java class that is similar to your app name and make it extend Application. Then add FacebookSdk.sdkInitialize

public class SocialMedia extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        FacebookSdk.sdkInitialize(getApplicationContext());
    }
}

Then add the name of this file to the application tag in your manifest:
android:name="SocialMedia"

This makes Android treat the SocialMedia file as a bit of an OnApplicationStart type file.


2) Add XML to layout


First add the xml for the button to your layout file where you want the user to see the big blue button.

<com.facebook.login.widget.LoginButton
  android:id="@+id/facebook_login_button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="30dp"
  android:layout_marginBottom="30dp" />

3) Add Java code to Activity

Now open up that view’s corresponding activity and add the following code:

a) Add the following two member variables at the top of the file:

LoginButton mFbLoginButton;
CallbackManager mCallbackManager;

b) Initialize these variables in onCreate

mCallbackManager = CallbackManager.Factory.create();

//Facebook button
mFbLoginButton = (LoginButton) findViewById(R.id.facebook_login_button);
mFbLoginButton.setReadPermissions("user_friends");

c) Register Callbacks for button clicks

mFbLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
  @Override
  public void onSuccess(LoginResult loginResult) {
     Log.i("socialmedia", "onSuccess");
     Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
     String fbToken = AccessToken.getCurrentAccessToken().getToken();
     Log.i("socialmedia", "fbToken:" + fbToken);
  }

  @Override
  public void onCancel() {
     Log.i("socialmedia", "FB onCancel");
     Toast.makeText(MainActivity.this, "FB onCancel", Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onError(FacebookException exception) {
     Log.i("socialmedia", "FB onError");
     Toast.makeText(MainActivity.this, "FB onError", Toast.LENGTH_SHORT).show();
  }
});

d) Add an onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

So hopefully that is all fairly self explanatory. The Login button opens a new Facebook window to confirm the user wants to share their details. mCallbackManager is responsible for receiving the result of that window and passing it to your callback. From there you can do what you want, copy the token and close the activity or whatever.

Hope it helps.