Google Plus & Facebook Login Integration Android Step By Step

To login with facebook first we need to create a project in Facebook developer site

Register your app : If you dont have an Account create one : Facebook Developer

Now Follow the steps:

Screen Shot 2016-08-21 at 11.56.08 AM

1st : Click on Add new App and select android

Screen Shot 2016-08-21 at 11.56.52 AM

2nd: Fill the form given to you and click on create app id

Screen Shot 2016-08-21 at 11.57.00 AM

3rd: 🙂 Humanity check Hope you are Human

4th: Product setup screen click on Facebook Login click on Save changes without making any changes and then click on dashboard

5th: You will get the App id And secret key

Now for google

1st: Goto this link Google Developer Follow The steps

2. Enabling G+ API on google console

In order to consume google plus services, first we need to enable the Google Plus API on google console and we need to register our digitally signed .apk file’s public certificate in the Google APIs Console.

2.1) Java keytool can be used to generate SHA-1 fingerprint. Open your terminal and execute the following command to generate SHA-1 fingerprint. If it ask for password, type android and press enter.

 

On windows

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

On Linux or Mac OS

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Screen Shot 2016-08-21 at 12.29.12 PM

2.2) Open Google APIs console

2.3) On the left, under APIs & auth section, click on APIs and on the right enable Google+ API service.

2.4) Now again on the left, click on Credentials and on the right, click on CREATE NEW CLIENT ID button. It will open a popup to configure a new client id.

2.5) In the popup, select Installed application as Application type.

2.6) Under Installed application type section select Android and give your project package name. This package name should be equal to your android project. I gave my package name as info.androidhive.gpluslogin

2.7) Enter your SHA1 fingerprint in Signing certificate fingerprint (SHA1) field.

2.8) Enable Deep Linking and click on Create Client ID button. Now you should see a new client created for your android application.

(Dont forget to add service.json you have got from google api integration you have to place it in your project root folder )

Now we are done with the server integeration

Code in android side are given below here we….

Keep in mind im working on my project which is shared on GITHUB there may be a chance of extra irrelevant code from login API But i have mentioned every where dont worry

Starting with manifest

manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.infiniteloops">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--Facebook-->
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
        <activity android:name=".login.Login_Activity"></activity>
        <!--Facebook-->
        <activity
            android:name=".HomeScreen"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".pkg_list_view.Simple_Listview"
            android:parentActivityName=".HomeScreen" />
        <activity
            android:name=".pkg_list_view.Custom_Listview"
            android:parentActivityName=".HomeScreen" />
        <activity
            android:name=".pkg_recycler_view.Simple_recycler_view"
            android:parentActivityName=".HomeScreen" />
        <activity
            android:name=".pkg_recycler_view.Custom_RecycelerView"
            android:parentActivityName=".HomeScreen" />
        <!--Facebook Login Start-->
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="FB Login" />
            </intent-filter>
        </activity>
        <!--Facebook login END-->
        <activity android:name=".login.HomeActivity"></activity>
    </application>

</manifest>

activity_login_.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame">

    <fragment
        class="info.infiniteloops.login.Login_Fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

main_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<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">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:orientation="vertical"
        android:layout_centerInParent="true"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView"
            android:layout_centerHorizontal="true"/>

        <com.facebook.login.widget.LoginButton
            android:id="@+id/login_button"
            style="@style/FacebookLoginButton"

            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <com.google.android.gms.common.SignInButton
            android:id="@+id/sign_in_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />

    </LinearLayout>
</RelativeLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#607D8B</color>
    <color name="colorPrimaryDark">#37474F</color>
    <color name="colorAccent">#E91E63</color>
</resources>

strings.xml

<resources>
    <string name="app_name">Infinite Loops Info</string>
    <string name="title_activity_home_screen">HomeScreen</string>
    <string name="facebook_app_id">1270899092928359</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_settings">Settings</string>
</resources>

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="FacebookLoginButton">

        <item name="android:layout_height">50dp</item>
        <item name="android:layout_marginTop">1dp</item>
        <item name="android:layout_marginBottom">1dp</item>
        <item name="android:layout_gravity">center_horizontal</item>
    </style>
</resources>

Build.gradle app level

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "info.infiniteloops"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:recyclerview-v7:+'
    compile 'com.android.support:cardview-v7:23.4.+'
    compile 'com.futuremind.recyclerfastscroll:fastscroll:0.1.5'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.android.gms:play-services-auth:9.4.0'

}
apply plugin: 'com.google.gms.google-services'

build.gradle Project LEVEL

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

LoginActivity.java Code

package info.infiniteloops.login;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;

import info.infiniteloops.R;


public class Login_Activity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_login_);

    }
    @Override
    public void onBackPressed()
    {
        // code here to show dialog
        finish();  // optional depending on your needs
    }
}

Login_Fragment.java

package info.infiniteloops.login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
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.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import info.infiniteloops.R;


/**
 * A placeholder fragment containing a simple view.
 */
public class Login_Fragment extends Fragment implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
    private CallbackManager callbackManager;
    private TextView textView;
    private static final String TAG = Login_Fragment.class.getSimpleName();

    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    //Signin button
    private SignInButton signInButton;
    private ProgressDialog pDialog;
    //Signing Options
    private GoogleSignInOptions gso;

    //google api client
    private GoogleApiClient mGoogleApiClient;

    //Signin constant to check the activity result
    private int RC_SIGN_IN = 100;
    SessionManager session;
    String email;
    public Login_Fragment() {

    }


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

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback&lt;LoginResult&gt;() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        // App code
                        Profile profile = Profile.getCurrentProfile();
                        displayMessage(profile);

                    }

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

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

        });

    session = new SessionManager(getContext());
        // Progress dialog
        pDialog = new ProgressDialog(getContext());
        pDialog.setCancelable(false);

        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity

        }
        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker= new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

            }
        };

        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
                displayMessage(newProfile);
            }
        };

        accessTokenTracker.startTracking();
        profileTracker.startTracking();


    }
    //GPLUS LOGIN
    //This function will option signing intent
    private void signIn() {
        //Creating an intent
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);

        //Starting intent for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onClick(View v) {
        if (v == signInButton) {
            //Calling signin
            signIn();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
    //END GPLUS LOGIN
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.main_fragment, container, false);

        LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);

        textView = (TextView) view.findViewById(R.id.textView);
        loginButton.setFragment(this);
        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback&lt;LoginResult&gt;() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                // App code
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("LoginActivity", response.toString());

                                // Application code
                                try {
                                    email = object.getString("email");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");
                request.setParameters(parameters);
                request.executeAsync();

                Profile profile = Profile.getCurrentProfile();
                displayMessage(profile);

            }

            @Override
            public void onCancel() {
                // App code
                Log.v("LoginActivity", "cancel");

            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Log.v("LoginActivity", exception.getCause().toString());

            }
        });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        //Initializing google signin option
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        //Initializing signinbutton
        signInButton = (SignInButton) view.findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        signInButton.setScopes(gso.getScopeArray());

        //Initializing google api client
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .enableAutoManage(getActivity() /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();


        //Setting onclick listener to signing button
        signInButton.setOnClickListener(this);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        callbackManager.onActivityResult(requestCode, resultCode, data);
        //If signin
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            //Calling a new function to handle signin
            handleSignInResult(result);
        }
    }
    @Override
    public void onStop() {
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }
    @Override
    public void onResume() {
        super.onResume();
        Profile profile = Profile.getCurrentProfile();
        displayMessage(profile);
    }

    //Get Plus Data
    //After the signing we are calling this function
    private void handleSignInResult(GoogleSignInResult result) {
        //If the login succeed
        if (result.isSuccess()) {
            //Getting google account
            session.setLogin(true);
            GoogleSignInAccount acct = result.getSignInAccount();
            //Displaying name and email
            textView.setText(acct.getDisplayName());
        } else {
            //If login fails
            //Toast.makeText(getActivity(), "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

    //Get FaceBook Data
    private void displayMessage(Profile profile){
        if(profile != null){
            textView.setText(profile.getName());
            session.setLogin(true);
        } else {
            //If login fails
            Toast.makeText(getActivity(), "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

}

SessionManager.java Code

package info.infiniteloops.login;
 
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class SessionManager {
    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();
 
    // Shared Preferences
    SharedPreferences pref;
 
    Editor editor;
    Context _context;
 
    // Shared pref mode
    int PRIVATE_MODE = 0;
 
    // Shared preferences file name
    private static final String PREF_NAME = "MyPreferences";
     
    private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
 
    public SessionManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.<h1>();
    }
 
    public void setLogin(boolean isL</h1>>n) {
 
        editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
 
        // commit changes
        editor.commit();
 
        Log.d(TAG, "User login session modified!");
    }
     
    public boolean isLoggedIn(){
        return pref.getBoolean(KEY_IS_LOGGEDIN, false);
    }
}

Keep that in mind you will have to match each and every file with your project with the above code.. I have removed my FACEBOOK Id, Google JSON you will have to add it by yourself

For full code fork me on GITHUB I love it