Loading ...

Integrating Facebook Login in Android | CodeAsp.Net

Integrating Facebook Login in Android

 /5
0 (0votes)

 To create an android application, you need to create an android studio project first. Follow these steps:

1. Create an android studio project and name it as "Facebook_Intergration_Example", and set the company domain as "codeasp.facebook_example.com". Click next.

2. Now select the minimum SDK as 18(Jelly Bean 4.3) and leave all other fields as they are and click next.

3. Select the activity as Blank Activity and click next.

4. Leave all the fields as default and click next.

5. Now open your "build.gradle(Project:Facebook_Intergration_Example)" file, and between  the "buildscript" and "dependencies" add the following code: 

repositories {
        mavenCentral()
    }

Your file will look like this:

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

buildscript {
    repositories {
        jcenter()
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'

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

allprojects {
    repositories {
        jcenter()
    }
}

6. Open the file "build.gradle(Module:app)" and under the dependencies add the following code:

compile 'com.facebook.android:facebook-android-sdk:4.1.0'

Your file will look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.facebook_example.codeasp.facebook_integratation_example"
        minSdkVersion 18
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'

}

7. Now, sync your project. Android studio will automatically add all the necessary data regarding the Facebook SDK.

8. Now open your manifest file and add the following lines of code:

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

You need to add this before adding any activity.

Now add the following code in your manifest file:

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

Note: this code is only added when we want to use the Facebook login feature.

After adding this your manifest file will look like this:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
<activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

 9. Now open your layout xml file "activity_main", here we will add the code to display the data received from facebook as well as the button to login to facebook.

Add the below code to your activity:

<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="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Name:" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Name" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="First Name:" />

        <TextView
            android:id="@+id/first_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="First Name" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Last Name:" />

        <TextView
            android:id="@+id/last_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Last Name" />
    </LinearLayout>

    <com.facebook.login.widget.LoginButton
        android:id="@+id/fb_login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

 10. Now in your "MainActivity" file, you need to initialise the Facebook SDK

 This is done by adding the code: 

FacebookSdk.sdkInitialize(getApplicationContext());

Now we can use the facebook services in our code file.

Add the following lines to your file, above your "onCreate" method:

private CallbackManager callbackManager;
private LoginButton fbLoginButton;

We need to initialize our Facebook SDK and also the callbackmanager, by adding the following lines under the onCreate method:

FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();

11. Now we will bind the TextView's and the login button in our xml file with our java file:

fbLoginButton = (LoginButton) findViewById(R.id.fb_login_button);
name = (TextView) findViewById(R.id.name);
first_name = (TextView) findViewById(R.id.first_name);
last_name = (TextView) findViewById(R.id.last_name);
gender = (TextView) findViewById(R.id.gender);

12. Now we will use the login button to connect to Facebook and get data from Facebook:

fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

//                System.out.println("Facebook Login Successful!");
//                System.out.println("Logged in user Details : ");
//                System.out.println("--------------------------");
//                System.out.println("User ID  : " + loginResult.getAccessToken().getUserId());
//                System.out.println("Authentication Token : " + loginResult.getAccessToken().getToken());
//                Toast.makeText(MainActivity.this, "Login Successful!", Toast.LENGTH_LONG).show();
                Profile profile = Profile.getCurrentProfile();
                name.setText(profile.getName());
                first_name.setText(profile.getFirstName());
                last_name.setText(profile.getLastName());

            }

            @Override
            public void onCancel() {
                Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
                System.out.println("Facebook Login failed!!");

            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
                System.out.println("Facebook Login failed!!");
            }
        });
    }

    @Override
    protected void onActivityResult(int reqCode, int resCode, Intent i) {
        callbackManager.onActivityResult(reqCode, resCode, i);
    }

13. Now we will have to create a Facebook application, where all the users will join. For that go to "developers.facebook.com", click on "My apps", then "Add a new app".

14. Now select "Android" as the platform.

15. Now select "Skip and Select an App ID". Give a name to the application e.g. "Demo_app" and category as "Education", you will be prompted with a security check box, complete it and you will be redirected to the application dashboard page.

16. Here copy the application id and save it in your strings file in your studio project:

<string name="facebook_app_id">819521074811920</string>

17. Now click on "Settings" tab from the left sidebar, and then click on "Add a platform" and select "Android".

    

18. Here enter the Google Package Name as "", Class name as "MainActivity" and enable the "Signle Sign On". Now we need to input the Key Hashes, and to generate them we have to write a method "printHashKey"

public void printHashKey(){
        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.facebook_example.codeasp.facebook_integratation_example",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("PrintMyHashKey:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }

Note: this method is only used to get the HashKey, once you have the key you can comment out this method.

19. In your android manifest file give the internet permission:

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

Finally your manifest file will look like this:

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

20. Get the Hash key from the "Log" and put that in the field requiring that, and click on save. If your project is not on the Google Play Store, then you will be prompted with a message regarding that, click on use this package name.

21. Now run your application on your phone or emulator.

       

To download the demo zip file: Click Here

Comments (no comments yet)

Top Posts