Facebook Authentication : Simple example of how to use Facebook login button in Android app

I will show a simple & step by step example of how to use Facebook SDK to Authenticate user. User will be able to grant permission to access the user details. So the app can continue with the details they received from Facebook or they can carry out actions on Facebook on their behalf.

 

Create Facebook New App ID

 

This is very crucial step in Authentication step. Click here and create new Facebook App Id.

 

 

 

 

Select a product. here it is “Facebook Login”

 

 

Select a platform

 

 

 

Complete the necessary fields,

 

 

Add the Facebook SDK in the Gradle file

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.appsgit.fbloginapp"
        minSdkVersion 20
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    compile 'com.facebook.android:facebook-android-sdk:[4,5)' //facebook sdk
    compile 'com.facebook.android:facebook-login:[4,5)' //login library
}

 

 

Don’t forget to mention MavenCentral in the Project level Gradle file

 

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

buildscript {
    repositories {
        jcenter()
        mavenCentral() //this is important to add facebook sdk
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

 

Press “SYNC” button in the top of the Gradle file. Everything will be added to your project now.

 

Add the Facebook Id to strings.xml file

<resources>
    <string name="app_name">FBLoginApp</string>
    <string name="facebook_app_id">361641477629334</string>
    <string name="fb_login_protocol_scheme">fb361641477629334</string>
</resources>

 

Add necessary fields in Android Manifest file

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

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


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

        <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="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

    </application>

</manifest>

 

Add Facebook login button to the main activity.

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.appsgit.fbloginapp.MainActivity">

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

</RelativeLayout>

 

package com.appsgit.fbloginapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

public class MainActivity extends Activity {

    CallbackManager callbackManager;

    LoginButton loginButton;

    AccessTokenTracker accessTokenTracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        loginButton.setReadPermissions("email");

        callbackManager = CallbackManager.Factory.create();

        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                Toast.makeText(MainActivity.this, "Successfuly logged in ", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                // App code
                Toast.makeText(MainActivity.this, "Cancelled...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Toast.makeText(MainActivity.this, "Login error ", Toast.LENGTH_SHORT).show();
                exception.printStackTrace();
            }
        });
    }

    /*
    * It is must to forward the result to callbackmanager.
    * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

 

You should see the following screen,

 

 

 

Press the button and type your username and passwords.

 

 

 

After you successfully logged in to the app, you will see the logout button,

 

 

 

Thats all folks,  You can check my personal Github for the complete source code.

I will try to cover many more interesting posts about Facebook integration in the future.  If you have anything in your mind to share with me please write it in the comment.

 

cheers..!!

 

 

 

About Zumry

Zumry Mohamed

Self Taught iOS & Android Mobile Application Developer.

Article written by zumrywahid

Self Taught iOS & Android Mobile Application Developer.

Be the first to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Fork me on GitHub