Facebook Integration - To provide the one click signup and signin process in the application, Android developers provide the login with social sites facilities like- facebook, twitter, linkedin, g+ etc. This tutorial guide you for facebook one click signup and signin process.
Steps to use login with facebook in your project.
- Crate a project in android studio.
- Open build.gradle(project) and add a repositories
repositories { mavenCentral() }
- Open build.gradle(app) and add a dependency
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
- Click on Sync Now.
- Now create an application on facebook developer console (Create Facebook application on developer consol).
- If you are on quick start then skip (6,7,8) steps else follow this-
- Select setting from left menu menu.
- Now scroll down the page and add android platform.
- A popup will be open then you select the android as a platform.
- A popup will be shown, Then you select the android as a platform.
- fill package name and first activity
- Now copy keyhash from logcat and fill here
- Now this setup has finished
- Select app review and click on make "Your $App_Name public?"
- Now check your application status on the dashboard. Green circle shows that your application is ready to integrate.
- Copy "App ID" and open your string.xml and add a string for facebook application id -
<string name="facebook_app_id">1460300553984844</string>
- Open your main_activity.xml and update it-
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="10dp" tools:context="com.pankaj.fb.integration.demo.MainActivity"> <!--Profile Pic--> <com.facebook.login.widget.ProfilePictureView android:id="@+id/ppview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="30dp" android:layout_marginTop="30dp" /> <!--Login Button--> <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_marginBottom="30dp" android:layout_marginTop="30dp" /> </LinearLayout>
- Open manifest and update it-
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.pankaj.fb.integration.demo"> <!--add permission--> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <!--activity--> <activity android:name="com.pankaj.fb.integration.demo.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--add meta data--> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" /> </application> </manifest>
- Open your MainActivity.JAVA class and update it -
package com.pankaj.fb.integration.demo; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.appevents.AppEventsLogger; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.facebook.login.widget.ProfilePictureView; import org.json.JSONException; import org.json.JSONObject; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; /* * * https://developers.facebook.com/apps/ * * */ public class MainActivity extends AppCompatActivity { //create objects private LoginButton loginButton; private CallbackManager callbackManager; private ProfilePictureView ppview; private HashMap<String, String> userData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); genrateKeyHash(); //__________initialize facebook sdk FacebookSdk.sdkInitialize(getApplicationContext()); //__________Activate application logger AppEventsLogger.activateApp(this); //__________set main activity view setContentView(R.layout.activity_main); //__________initialize objects loginButton = (LoginButton) findViewById(R.id.login_button); ppview = (ProfilePictureView) findViewById(R.id.ppview); callbackManager = CallbackManager.Factory.create(); //__________set permission for access required data loginButton.setReadPermissions("email,public_profile"); //__________check for already login if (AccessToken.getCurrentAccessToken() != null) { //__________set image if already login ppview.setProfileId(AccessToken.getCurrentAccessToken().getUserId()); } fbLogin(); } public void fbLogin() { //__________Callback login loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { //__________user image url final String image = "https://graph.facebook.com/" + AccessToken.getCurrentAccessToken().getUserId() + "/picture?type=large&width=720&height=720"; //__________Create a graph request GraphRequest request = GraphRequest.newMeRequest( AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { //__________process this data Log.e("response", response.toString()); Log.e("object", object.toString()); Log.e("image", image); try { //_______put data into user data map userData = new HashMap<String, String>(); userData.put("id", object.get("id").toString()); userData.put("email", object.get("email").toString()); userData.put("name", object.get("name").toString()); } catch (JSONException e) { e.printStackTrace(); } //__________set user image ppview.setProfileId(AccessToken.getCurrentAccessToken().getUserId()); //___________show the detail in toast message Toast.makeText(MainActivity.this, "Name : " + userData.get("name") + "\nEmail : " + userData.get("email") + "\nID : " + userData.get("id"), Toast.LENGTH_SHORT).show(); } }); //__________add parameters for required data Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email"); request.setParameters(parameters); //__________eqecute request request.executeAsync(); } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); } //____________genrate key has private void genrateKeyHash() { try { PackageInfo info = getPackageManager().getPackageInfo("com.pankaj.fb.integration.demo", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } }
- Now all the development steps for Login with facebook has completed, Please run the application and see the screen of device.
- Now click on "Login with facebook" and see the screen -
Fill the credential
- Now yow will see a screen to got permission click on "Continue" and see the screen -
- Now see the logcate section-
- Finally login with facebook has completed and you got data(id,name,email and profile picture), please see the screen-
- Good bye, Thanks to read this blog.