I’m writing this blog post because I couldn’t find a proper tutorial which explains, adding Facebook Sign-In to android project with all new Google Firebase properly.This post will explain you how to add Facebook login to your android application using Google Firebase authentication. So let’s start,
Create your Firebase project from Firebase Console and select Android as your platform.
Then add your project’s package name and SHA-1 key in the prompted view as shows below.
How to generate a SHA -1 key Step by Step
- Download openssl
- Extract openssl zip and create a folder OpenSSL in C:/ and copy the extracted code
- Now go to your Java bin folder ( C:\Program Files (x86)\Java\jre1.8.0_25\bin )
- Now open the command prompt inside the bin folder and execute the following command
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias
androiddebugkey -storepass android -keypass android
This command will generate a SHA-1 key under “Certificate fingerprints” in cmd.Copy SHA-1 and paste it in your firebase project.
After adding a package name and SHA-1 key(completing the first step) Firebase will generate a json file in the second step and it will be automatically downloaded to your device.
Copy the json file and paste it in the project’s module app/ folder.
Since we have added json file to our android project we need to sync our android project with google service.In order to do that add following code to your Project’s gradle file and sync.
buildscript { // ... dependencies { // ... classpath 'com.google.gms:google-services:3.0.0' } }
And add the following dependencies in your Module’s gradle file
dependencies {
compile 'com.google.firebase:firebase-core:9.2.1'
}
add the following code at the bottom of the gradle file and Sync the gradle file with the changes.
apply plugin: 'com.google.gms.google-services'
Enabling Facebook Sign-in on Firebase
Please follow these steps to enable Facebook Sign-In
- Go to your Firebase project console
- Click Auth under Develop section
- Select Sign-in method tab and enable Facebook Sign-In by giving Facebook App Id and App Secret
To create a Facebook App please click here
Generate a Key hash for Facebook App
In order to continue with your Facebook Application you may need to add a Key hash for your Facebook App.So here is what you need to do,
If you haven’t installed OpenSSL in your machine,please follow these steps.
- Download openssl
- Extract openssl zip and create a folder OpenSSL in C:/ and copy the extracted code
else,
- Go to your Java bin folder ( C:\Program Files (x86)\Java\jre1.8.0_25\bin )
- Now open the command prompt inside the bin folder and execute the following command
- Provide password “android” as when you are prompted.
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | "C:\OpenSSL\bin\openssl" sha1 -binary | "C:\OpenSSL\bin\openssl" base64
This will generate a unique key hash for your android application.
Implementing the Facebook-Login Activity
To start working with Facebook authentication we need to add Firebase Authentication dependencies to our android project. Please add the following dependency in your app-level gradle and compile.
compile 'com.google.firebase:firebase-auth:9.2.1'
and to add Facebook SDK to our android project please add the following dependency to app-level gradle and compile.
compile 'com.facebook.android:facebook-android-sdk:4.14.0'
Check the latest Facebook SDK version from here.
After the gradle sync if you get an error like this “No resource found that matches the given name (at ‘cardBackgroundColor’ with value ‘?android:attr/colorBackgroundFloating’)”. Please add the following dependecy to your app-level gradle and Sync.
compile('com.android.support:cardview-v7:23.2.0') { force = true }
Add the Following code to AndroidManifest.
<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 create a new layout in your projects folder.I’m going to name my layout as activity_facebooklogin. add the following code inside your layout.
<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" />
I’m going to add a new activity called FacebookLoginActivity and I will implement Facebook login button in this activity.
package com.cnf271.testapplication; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; 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.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FacebookAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import java.util.Arrays; /** * Created by Cnf on 8/3/2016. */ public class FacebookLoginActivity extends AppCompatActivity{ private LoginButton loginButton; private CallbackManager callbackManager; private FirebaseAuth firebaseAuth; private FirebaseAuth.AuthStateListener firebaseAuthListner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(this.getApplicationContext()); setContentView(R.layout.activity_facebooklogin); callbackManager = CallbackManager.Factory.create(); loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setReadPermissions(Arrays.asList("email")); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { handleFacebookAccessToken(loginResult.getAccessToken()); } @Override public void onCancel() { Toast.makeText(getApplicationContext(),"Cancel",Toast.LENGTH_SHORT).show(); } @Override public void onError(FacebookException error) { Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show(); } }); firebaseAuth = FirebaseAuth.getInstance(); firebaseAuthListner = new FirebaseAuth.AuthStateListener(){ @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if(user != null){ goMainScreen(); } } }; } private void handleFacebookAccessToken(AccessToken accessToken) { AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken()); firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(!task.isSuccessful()){ Toast.makeText(getApplicationContext(),R.string.firebase_error_login, Toast.LENGTH_LONG).show(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode,resultCode,data); } @Override protected void onStart() { super.onStart(); firebaseAuth.addAuthStateListener(firebaseAuthListner); } @Override protected void onStop() { super.onStop(); firebaseAuth.removeAuthStateListener(firebaseAuthListner); } public void goMainScreen(){ Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
Please add the following code to your strings.xml file.
<string name="firebase_error_login">Firebase Login Error</string> <string name="facebook_app_id">YOUR APP ID</string>
Add the following code to AndroidManifest file.
<activity android:name=".FacebookLoginActivity"> <intent-filter> <action android:name="android.intent.action.VIEW" /> </intent-filter> </activity> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
Please add the following code to your MainActivity.
package com.cnf271.testapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.view.View; import com.facebook.AccessToken; import com.facebook.FacebookSdk; import com.facebook.login.LoginManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(this.getApplicationContext()); setContentView(R.layout.activity_main); if (AccessToken.getCurrentAccessToken() == null) { goLoginScreen(); } } private void goLoginScreen() { Intent intent = new Intent(this, FacebookLoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } public void logout(View view) { LoginManager.getInstance().logOut(); goLoginScreen(); } }
Make sure to initialize the Facebook sdk before setting the ContentView.(check onCreate method)
That’s all folks. If you have done everything according to the post Application will run and Facebook Login layout will pop up and once you have logged in using your Facebook credentials you will be redirected to hello world Main layout.
(Mobile Application images)
(Firebase Users table)
Please download the project’s source files from my Github.
Thanks. Stay tuned for more posts.