Facebook Login integration in android

15/04/2017   03:39:47 PM

Hello in this android article we will create an android application and in that application integrate Facebook Login using Facebook SDK 4.

using this you can easily login to android application without any registration or mail verification because facebook already did it.so lets start the tutorial

 

1. Create App on Facebook developer’s website for that go on https://developers.facebook.com/docs/android

 

2. Click on getstarted

 

facebook login integration in android

 

3. Click on Quick Start for Android

 

facebook login integration in android

 

 

4. Login using your facebook login details

If you not register on facebook, register here as a developer

 

facebook login integration in android

 

 

5. Click on skip and create new App id

 

facebook login integration in android

 

 

6. Enter details about app & click on Create AppId

 

facebook login integration in android

 

Observe following details

It have app version, App Id, App Seceret

Here we need to use App Id in to android project in android studio  

 

7.Create a new project in android studio

In this project Package name is com.xperiaitinnovations.fbloginsample and Class name is MainActivity   

 

8. Now click on settings option present in left menu bar of  your facebook developers website 

 

9. Click on Add platform

 

10. Select android

 

facebook login integration in android

 

 

11.Observe below screen need to add google play package name, Class name, Key Hashes so for that

add google play package name, Class name

In this project Package name is com.xperiaitinnovations.fbloginsample and Class name is MainActivity   

 

facebook login integration in android

 

 

12. Click on save changes

 

13.Now back again to android studio where we creates a project to add facebook SDK in android project

  add the following code 

 Add this to Module-level /app/build.gradle

repositories

{

mavenCentral()

}

 Add the following compile dependency to  app/build.gradle file in dependency code block  with latest version of the Facebook SDK

compile 'com.facebook.android:facebook-android-sdk:4.+'

 

14.Now click on sync option to synchronize project

android studio will download Facebook SDK after sync

 

15. After project build  without any error add the following code in MainActivity.java to genrate HASHKEY

 

import android.app.Application;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

 

public class MyApplication extends Application {

@Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
HashkeyGenrate();
}

private void HashkeyGenrate() {
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.xperiaitinnovations.fbloginsample",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
// System.out.println("HASHKEY:"+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
Log.d("HASHKEY:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}
}
}

 

16.Now click on sync now to synchronize projectàandroid studio download Facebook SDK after sync

 

17. After build project without any error add the following code in MainActivity

 

import android.app.Application;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;

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

 

18.Add Facebook App ID which we early created in facebook developers website to your android studio project's strings file  

 Example path: /app/src/main/res/values/strings.xml.

<resources>
<string name="app_name">LoginSample</string> //here LoginSample in Display Name which we added in facebook developers website when create app
<string name="facebook_app_id">your facebook app id</string>
</resources>

 

19. In AndroidManifest.xml Add a uses-permission element to the manifest:

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

 

20. Add a meta-data element to the application element In AndroidManifest.xml

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

 

21.Run your android application and HASHKEY will be genrate, copy this HASHKEY from Logcat window of android studio and paste 

it to your facebook developers website settings/android option

 

22.Click on save changes Now All three things completed

1)Package Name2)Class Name3)Key Hashes

 

23.Implement Login in android studio project,for that add facebook Activity to AndroidManifest.xml file

<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" />

 

24.Add one fragment activity in android studio project  

 

25.Initializing login button to fragment-main.xml layout file 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xperiaitinnovations.fbloginsample.MainFragment"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/text_details"
        />
    <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_centerInParent="true"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp" />
</RelativeLayout>

 

26.Add call back manager object

CallbackManager -

Use to route calls back to the Facebook SDK and your registered callbacks. You should call it from the initiating activity or fragments onActivityResult call.

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainFragment extends Fragment {
    private CallbackManager callbackmanager;
    private TextView tv;
    private FacebookCallback<LoginResult> callback= new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            //current token to connect to facebook servers

            AccessToken accessToken=loginResult.getAccessToken();
            Profile profile=Profile.getCurrentProfile();
           display(profile);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    };
    public MainFragment() {
    }
public void display(Profile profile)
{
    if(profile!=null)
    {
        tv.setText("Welcome:"+profile.getName());
    }
}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
        callbackmanager=CallbackManager.Factory.create();

        //AppEventsLogger.activateApp(this);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackmanager.onActivityResult(requestCode,resultCode,data);
    }
    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LoginButton login= (LoginButton)view. findViewById(R.id.login_button);
        tv= (TextView) view.findViewById(R.id.text_details);
        login.setReadPermissions("user_friends");
        login.setFragment(this);
        login.registerCallback(callbackmanager,callback);
    }

    @Override
    public void onResume() {
        super.onResume();
        Profile profile=Profile.getCurrentProfile();
        display(profile);
    }
}

 

27.Finally Run your android application and login to your android application using your facebook username and password.


Output

                   

Support us by Sharing