Call us at +91-9810869242
E-mail: info@dezyne.in

Business Blog

What We have Done Lately

Social Media Login Integration in Android App- Part I (Facebook Login)

Share Us :

So what is the first thing we all do in the morning. Getting up, switching on the internet and opening your social media accounts. The very existence of social media and it’s ever growing usage has made it an amazing platform to be used as a basic information retriever for the developers. So, if you too are planning to integrate a social media login into your android app, here is a basic guide that will explain every minor details, with great simplicity.

So first step, Create a new Project or if you want to add it to your existing application skip this step(Keep in mind the minimum required  API level 15(Android 4.0.3 ).

Now go to your app’s  built.gradle(Module:app).

Add the following before ‘dependencies’ code to it :-

repositories { mavenCentral() }

and add the following dependencies in it  :-

compile ‘com.facebook.android:facebook-android-sdk:4.+’

Now, compile the gradle to see for any errors. If no errors are present proceed further, otherwise check you sdk version and gradle dependencies.

Go to the application class from which you want to launch the Facebook login and add the following code in the ‘onCreate’ method:-

// Add this to the header of your file:
import com.facebook.FacebookSdk;                             //import this 

public class MyApplication extends Application {
    // Updated your class body:
    @Override
    public void onCreate() {
        super.onCreate();
        // Initialize the SDK before executing any other operations,
        FacebookSdk.sdkInitialize(getApplicationContext());  //add this line
        AppEventsLogger.activateApp(this);                   //add this line
    }
}

Now go to https://developers.facebook.com/docs/android/getting-started and log in or make a facebook id and register your app and that will generate an app id save that in your strings.xml with a name ‘facebook_app_id’ . Now go to your AndroidManifest.xml file and add:-

<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="@string/app_name" ...>           //where app_name is the name of your app that you have to create in your strings.xml
    ...
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    ...
</application>

Also add a FacebookActivity in your AndroidManifest.xml

<activity android:name="com.facebook.FacebookActivity"
          android:configChanges=
                 "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:theme="@android:style/Theme.Translucent.NoTitleBar"
          android:label="@string/app_name" />

Now you have to generate an android key hash for the facebook app which you can easily get by putting this code in any of your application methods and running the application once:-

try {
              info = getPackageManager().getPackageInfo("in.dezyne.mockinterview", PackageManager.GET_SIGNATURES);
              for (Signature signature : info.signatures) {
                  MessageDigest md;
                  md = MessageDigest.getInstance("SHA");
                  md.update(signature.toByteArray());
                  String something = new String(Base64.encode(md.digest(), 0));
                  //String something = new String(Base64.encodeBytes(md.digest()));
                  Log.e("hash key", something);
              }
          } catch (PackageManager.NameNotFoundException e1) {
              Log.e("name not found", e1.toString());
          } catch (NoSuchAlgorithmException e) {
              Log.e("no such an algorithm", e.toString());
          } catch (Exception e) {
              Log.e("exception", e.toString());
          }

Now place that hash key in your facebook app hash key and save changes. Now you are almost done place this custom facebook button the activity or fragments xml from where you want the user to log in.

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

Now in the ‘onCreateView’ of the activity or fragment, place the following code:-

@Override
public View onCreateView(
        LayoutInflater inflater,
        ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.splash, container, false);

    loginButton = (LoginButton) view.findViewById(R.id.login_button);
    loginButton.setReadPermissions("email");
    // If using in a fragment
    loginButton.setFragment(this);    
    // Other app specific specialization

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
        }

       @Override
        public void onCancel() {
            // App code
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
        }
    });    
}

You then need to call FacebookSdk.sdkInitialize to initialize the SDK, and then callCallbackManager.Factory.create to create a callback manager to handle login responses. Here’s an example of adding the callback in a fragment:

public class MainActivity extends FragmentActivity {
    CallbackManager callbackManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.usersettings_fragment_login_button);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { ... });
    }

Now you add the callback to your activity or fragment’s onCreate() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());

    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
@Override public void onSuccess(LoginResult loginResult) { // App code } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); }

Then in the OnActivityResult() forward the login results to the callbackManager created in onCreate():

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

After all these steps you are good to go with the facebook login integration in your android app. But you can also customize the permission and the button appearance of the facbook login button. I hope this tutorial will help you with the facebook integration and have helped you. So this is it for this post, see you later with the next part of this blog with another social media platform login integration.

Share Us :
Share:
August 11, 2016
dezyneadmin
3DTechunity
No Comments