In this tutorial, we will learn Integrating Facebook, Twitter and Google in Android for Login in our android app. Let’s start. First, we need to create a project in Android Studio. Read on and find out.
What is Social Login Integration?
- If you want to authenticate a user in your app without asking him/her to fill signup form, then integrating your app with any social site is the best way to do it. It will allow a user to login with google, facebook or twitter and use their details. It won’t require filling the complete process to login in your app.
TUTORIAL
GETTING STARTED WITH FACEBOOK:
- Facebook provides its native android SDK, so we’re going to use its services. Now, let’s see how to integrate facebook login in our app.
1. Create sample application
- In Android Studio, go to File -> New Project. When asked about the main screen, select an Empty Activity. Call this activity MainActivity. Set up the emulator or use your android phone. After completing, run that simple app.
2. SETUP THE REPOSITORY AND DEPENDENCIES
- In android Studio sidebar, look for Build.gradle file associated with the project and add the following code.
buildscript { repositories { mavenCentral() // <– add this line } }
- After adding this line, your project will request to Sync. Wait until the gradle-building is completed. Then, go to build.gradle file associated with the app module and add the following code. Also import Facebook.
dependencies { // (...) compile 'com.facebook.android:facebook-android-sdk:4.6.0' // (...) compile 'junit:junit:4.12' }
import com.facebook.FacebookSdk;
2.Tell Facebook About Your App
- Go to https://developers.facebook.com/apps and click Add a New App.
- After Creating ID, go to settings -> Basic.
- At the bottom, we can see a button called +Add Platform, just click on that and select Android. There, you will see the main class, Package name and hash key.
“The hash key is going to identify your app to Facebook database servers.” We will generate hash key later, now we need to do some important work in our android studio project. Follow the steps below.
3. SETUP THE SDK IN YOUR ANDROID PROJECT:
- Now go to the Strings.xml file in layout and add the facebook app ID as facebook_app_id. In our case, the app id is 1702416153410004
- <string>name=”facebook_app_id”>1702416153410004</string>.
- Edit your AndroidManifest.xml file and add the internet permission and the facebook app ID as meta-data and also add the facebook activity. Follow the codes below.
1.Internet permission:
<uses-permission android:name="android.permission.INTERNET"/>
2.Meta Data:
<meta-data android:name="com.facebook.sdk.ApplicationId"android:value="@string/Faceboob_app_id"/>
3.Facebook Activity:
<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" />
4. ADD THE FACEBOOK LOGIN BUTTON:
- The Facebook SDK for Android comes with a convenient button that can be added easily to our activities and add the following code in activity_main.xml file in layout.
<?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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <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" /> </LinearLayout>
- Now, we’re going to jump to MainActivity.java and do the necessary SDK initialization in your app. Add the following code.
package icoderslab.com.sociallogin; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import java.util.concurrent.Callable; public class MainActivity extends AppCompatActivity { private LoginButton mFacebookSignInButton; private CallbackManager mFacebookCallbackManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); //facebook mFacebookCallbackManager = CallbackManager.Factory.create(); mFacebookSignInButton = (LoginButton) findViewById(R.id.login_button); mFacebookSignInButton.registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(final LoginResult loginResult) { //TODO: Use the Profile class to get information about the current user. handleSignInResult(new Callable<Void>() { @Override public Void call() throws Exception { LoginManager.getInstance().logOut(); return null; } }); } @Override public void onCancel() { handleSignInResult(null); } @Override public void onError(FacebookException error) { Log.d(MainActivity.class.getCanonicalName(), error.getMessage()); handleSignInResult(null); } } ); } private void handleSignInResult(Object o) { //Handle sign result here }
- And finally, add the onActivityResult method outside the onCreate method.
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mFacebookCallbackManager.onActivityResult(requestCode, resultCode, data); }
5. FINDING HASH KEY FOR FACEBOOK:
Lastly, we’re going to learn how to generate a hash key and add the key in our app so that it can identify our app because the hash key is truly unique.
- Download Openssl
- Make an OpenSSL folder in C drive
- Extract Zip files into this OpenSSL folder created in C Drive.
- Copy the File debug.keystore from .android folder in my case (C:\Users\SYSTEM.android) and paste into JDK bin Folder in my case (C:\Program Files\Java\jdk1.6.0_05\bin)
- Open the command prompt and give the path of JDK Bin folder in my case (C:\Program Files\Java\jdk1.6.0_05\bin).
- Copy the following code and hit enter “keytool -exportcert -alias androiddebugkey -keystore debug.keystore > c:\openssl\bin\debug.txt”
- Now you need to enter the password. Password = android.
- If you see in OpenSSL Bin folder, you will get a file with the name of debug.txt
- Now either you can restart command prompt or work with existing command prompt
- Get back to C drive and give the path of OpenSSL Bin folder
- Copy the following code and paste “OpenSSL sha1 -binary debug.txt > debug_sha.txt” you will get debug_sha.txt in OpenSSL bin folder
- Again copy following code and paste“OpenSSL base64 -in debug_sha.txt > debug_base64.txt”
- You will get debug_base64.txt in OpenSSL bin folder
- Open debug_base64.txt file Here is your Key hash.
6. Adding Hash key
- Now you have got your hash key so add that key in Facebook Developers site and save changes.
- After saving this info, you have successfully linked your app with facebook by giving the package name and hash key.
- Go back to Android Studio and run your app.
7. Error App Not Setup:
- You might get this error if the app is running on another mobile.
- You need to allow your app public if you want to publish your app on app store.
- Follow steps below.
- Go to https://developers.facebook.com/apps/
- Select your app.
- Select “App review.”
- As you can see in above wizard, “Make AppName public?”
- Turn this into YES and save changes.
That’s it. You have successfully integrated your app and also made it public.
OUTPUT
- Twitter also provides a native SDK for Android. Let’s see how we can integrate it.
- Create a simple project as we described above. You need to download the Fabric plugin for the android studio from https://get.fabric.io/android?locale=en-us. Sign in and download the plugin.
3. Adding Fabric Plugin
Alright, now we have to navigate the plugin in the android studio.
- Open Android studio and Go to Settings -> Plugins and select Install from disk.
- Browse your location where you downloaded the fabric plugin and Click Ok.
- Once the plugin is installed, create a new project. At right side corner, you can see Fabric bar. Click on that and turn on. Follow wizard.
- You will see a list of fabric Kits and we have to use Twitter so Click on Twitter.
- Now you have to install twitter.
- After installation add twitter to your project. Click on Apply.
- Now it will take some time to add the dependencies and plugins. You will see some changes in Build.gradle(Project) and Build.gradle(app_module) files. After build gradle is finished.
3. Adding Login Button in activity_main.xml file.
<com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/twitter_sign_in_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" />
4. Implementing CallBack Method
package icoderslab.com.sociallogin; import com.twitter.sdk.android.Twitter; import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.Result; import com.twitter.sdk.android.core.SessionManager; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterCore; import com.twitter.sdk.android.core.TwitterException; import com.twitter.sdk.android.core.TwitterSession; import com.twitter.sdk.android.core.identity.TwitterLoginButton; import io.fabric.sdk.android.Fabric; public class MainActivity extends AppCompatActivity { // Note: Your consumer key and secret should be obfuscated in your source code before shipping. private static final String TWITTER_KEY = "izRZ3BRpL1jrpSniSJYAI91AV"; private static final String TWITTER_SECRET = "PtboEJCcxuGSA3cxuukTkMlauCminR8zADX3LHymJxDrv6tuzL"; private TwitterLoginButton loginButton; loginButton = (TwitterLoginButton) findViewById(R.id.twitter_sign_in_button); loginButton.setCallback(new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { String UserName = result.data.getUserName(); Toast.makeText(MainActivity.this, UserName, Toast.LENGTH_LONG).show(); } @Override public void failure(TwitterException exception) { } });
5. Add The OnActivityResult method
- This method must be outside OnCreate() method
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); loginButton.onActivityResult(requestCode,resultCode,data); } }
That’s it, run the app.
OUTPUT:
- Google also provides native android SDK to handle logins.
1. INSTALL GOOGLE PLAY SERVICES
- Make sure the Google Play Services are available.
- Go to tools -> Android -> SDK Manager -> SDK Tools .
- In Extras section, make sure the google play services is available and enabled.
2. Setting up repositories and dependencies:
- Open build.gradle of your project and add the Google play services classpath.
buildscript { // (...) dependencies { // (...) classpath 'com.google.gms:google-services:1.5.0-beta2' // (...) } }
- Now, open build.gradle of your app module and add the Google Play Services plugin and Compile time dependency.
apply plugin: 'com.google.gms.google-services' dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' // (...) compile 'com.google.android.gms:play-services-auth:8.3.0' // (...) }
3. Authenticate your app with Google:
- Go to https://developers.google.com/mobile/add?platform=android.
- Add your app, it will ask your app name and android package name. After this, Google will provide you its services and we have to choose Google sign in.
- Click on “Choose and configure services.”
- Choose “Google Sign In.” Here we can see google is asking for “Android Signing Certificate SHA-1.” Let’s see how to find this key. There are two ways. I will explain the simplest one.
- Open Your Project.
- Click on Gradle (From Right Side Panel, you will see Gradle Bar).
- Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of your Project).
- Click on Your Project (Your Project Name from List).
- Click on android-> signingReport and see the magic.
4. Download google-services.json
- Now you have your SHA1 key as you can see in above wizard which I have marked black (because it’s confidential). Paste this key to google developer console and continue. And there you can download Google services JSON.
5. Adding Google-service file to Project:
☛ Click on “ADD App” button in order to create “google-services.json” file.
- You will get a popup to save “google-services.json.”
- ADD “google-services.json” file in app file of your project.
6. Add Google Sign Button in activity.xml
<com.google.android.gms.common.SignInButton android:id="@+id/google_sign_in_button" android:layout_width="300dp" android:layout_height="40dp" android:layout_gravity="center" />
7. Bind the button to your callback method inside the OnCreate method:
package icoderslab.com.sociallogin; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.google.android.gms.common.SignInButton; import java.util.concurrent.Callable; public class MainActivity extends AppCompatActivity { private SignInButton mGoogleSignInButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogleSignInButton = (SignInButton) findViewById(R.id.google_sign_in_button); findViewById(R.id.signOut); mGoogleSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signInWithGoogle(); switch (v.getId()) { // ... case R.id.signOut: signOut(); break; } } }); } private void signOut() { } private void signInWithGoogle() { }
8. Handle SignInWithGoogle() Method:
private static final int RC_SIGN_IN = 9001; private void signInWithGoogle() { if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); final Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { } }); }
9. Add The OnActivityResult method:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if(result.isSuccess()) { final GoogleApiClient client = mGoogleApiClient; result.getSignInAccount(); } else { //handleSignInResult(...); } } else { // Handle other values for requestCode } } }
- Now you can add the login details in handleSignInresult method. For example, if you want to see user details, use result.getSignInAccount();
Complete Main.activity.java code:
package icoderslab.com.sociallogin; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import java.util.concurrent.Callable; public class MainActivity extends AppCompatActivity { private SignInButton mGoogleSignInButton; private GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogleSignInButton = (SignInButton) findViewById(R.id.google_sign_in_button); findViewById(R.id.signOut); mGoogleSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signInWithGoogle(); switch (v.getId()) { // ... case R.id.signOut: signOut(); break; } } }); } private static final int RC_SIGN_IN = 9001; private void signInWithGoogle() { if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); final Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if(result.isSuccess()) { final GoogleApiClient client = mGoogleApiClient; result.getSignInAccount(); } else { //handleSignInResult(...); } } else { // Handle other values for requestCode } }
That’s all for Google Sign In integrating with your app.
Final Output of Facebook-Google-Twitter:
That’s all for Integrating Facebook, Twitter and Google in Android. You have now successfully integrated your app with popular social networks.
Leave a Reply