Skip to main content

Implementing Facebook Login Using Android SDK


Facebook Login allows you to obtain a token to access Facebook's API on behalf of someone using your app. You can use this feature in place of building your own account system or to add Facebook services to your existing accounts.

To properly handle Facebook Login using the Facebook for Android app, make the following changes in the App Dashboard.


Create a Facebook App
URL to create FB App:
Once created, note down the app ID shown at the top of the dashboard page. You'll need to add this to your project files.


Next, you will also need to associate your Android keys hashes with the app. The key hash is used by Facebook as a security check for authenticity. By default, the app's package is signed with a machine specific debug key. When publishing the app it is typically signed with a different, release key. Therefore, you want to make sure you have the hashes of all the related keys set on Facebook:
Go to 'Settings' in the left nav, then click on the 'Add Platform' button, and select Android. Add the debug key hash that you obtained at the end of the previous step with the keytool app:

If you have a release key, you will need to add its hash in the same way. To obtain the release key hash, use the 'keytool' in the same way as in the steps above except for the alias and path. On OS X, run:
On Windows, use:
keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64
Make sure to use the password that you set when you first created the release key.
Save this change.
You will also need to return to this dashboard and add your app's package name and main activity class once you have created a new Android project itself.
If you don’t have openssl please download from below location:
Command to create App ID: [Example]
keytool -exportcert -alias quesponkey -keystore "C:\Users\Sujay.A\Documents\quespon\keystore.keystore" | "C:\Users\Sujay.A\Documents\ Facebook_RND\openssl-0.9.8k_X64\bin\openssl.exe" sha1 -binary | "C:\Users\Sujay.A\Documents\ Facebook_RND\openssl-0.9.8k_X64\bin\openssl.exe" base64


Download Facebook SDK from below location:
Import the SDK into Eclipse

Select only FacebookSDK from that and import that.
Create a new Android Project with Facebook Login
Create a new Android Application Project in Eclipse, using 'File' > 'New' > 'Project...' and select 'Android Application Project':
Finish the wizard, and your new project will have been created, along with the main activity class:

Register the package and activity with Facebook
Link to the SDK project and configure the Facebook app ID
package com.firstandroidapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
import com.facebook.*;
import com.facebook.model.*;
 
public class MainActivity extends Activity {
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    // start Facebook Login
    Session.openActiveSession(this, true, new Session.StatusCallback() {
 
      // callback when session changes state
      @Override
      public void call(Session session, SessionState state, Exception exception) {
        if (session.isOpened()) {
 
          // make request to the /me API
          Request.newMeRequest(session, new Request.GraphUserCallback() {
 
            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user, Response response) {
              if (user != null) {
                TextView welcome = (TextView) findViewById(R.id.welcome);
                welcome.setText("Hello " + user.getName() + "!");
              }
            }
          }).executeAsync();
        }
      }
    });
  }
 
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
  }
 
}
 
At this point, you should return to the App Dashboard on the Facebook Developers site and add your Android app's package and activity names. To do this, in the app dashboard, go to 'Settings' on the left nav and there, in the Android section, complete the two missing fields. Also enable 'Single Sign On':

Returning to Eclipse, your new application needs to be linked to the SDK library project. View the properties for the project, and navigate to the 'Android' tab. In the lower part of the dialog, click 'Add' and choose the 'FacebookSDK' project from the workspace:

To add the Facebook app ID into your project, open up the strings.xml file in the res/values folder of your project. You need to add an app_id string containing the ID you obtained in the previous step.

(If you view the source of the strings.xml file, you will see the resulting <string name="app_id">497906953566757</string> in the document.)
Next, open the AndroidManifest.xml file in the root of the project. Add a 'Uses Permission' item named android.permission.INTERNET:

Also, in the 'Application' tab, add a 'Meta Data' item called com.facebook.sdk.ApplicationId, with a value of the app_id string you just configured:

Finally, add a new Activity to the app, with the name com.facebook.LoginActivity

(Again, if you check the source of the file, you should see the three corresponding new lines in the XML,<uses-permission android:name="android.permission.INTERNET"/>, <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>, and <activity android:name="com.facebook.LoginActivity"/>)


Output:




Comments

Popular posts from this blog

Short explanation on Gradle, minSdkVersion, maxSdkVersion, compileSdkVersion and targetSdkVersion in Android

Gradle : The Android build system compiles app resources and source code, and packages them into APKs that you can test, deploy, sign, and distribute. Android Studio uses Gradle . The Android plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications. Gradle and the Android plugin run independent of Android Studio. Gradle architecture is shown below. Example: android { compileSdkVersion 27 buildToolsVersion “26.0.2” defaultConfig { applicationId “com.example.checkyourtargetsdk" minSdkVersion 15 targetSdkVersion 27 versionCode 1 versionName “1.0” } } minSdkVersion : minSdkVersion is the lower bound for your app . The minSdkVersion is one of the signals the Google Play Store uses to determine which of a user’s devices an app can be installed on.  your app’s minSdkVersion must be at least as high as your dependencies’ minSdkVe

Google re-branded the support Android libraries to AndroidX

It is important to note, you cannot mix AppCompat and Jetpack in the same project. You must convert everything to use Jetpack if you want to upgrade. The support library artifacts are being deprecated and all future development is going into AndroidX , so there's no avoiding this migration. Alan Viverette sums this up nicely: “There won’t be a 29.0.0, so Android Q APIs will only be in AndroidX” The stable release of 28.0.0 will be the final feature release packaged as android.support . All subsequent feature releases will only be made available as androidx-packaged artifacts. Below tips will give you a clearer transition path. The current version of AppCompat (v28.x) is exactly the same as AndroidX (v1.x). In fact, the AppCompat libraries are machine generated by changing maven coordinates and package names of the AndroidX codebase. For example, android.support.v7.app.AppCompatActivity is now androidx.appcompat.app.AppCompatActivity For a complete listi

Android Beginners Guide

                                                                                                               Android Operation System: Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM). Android is created by the Open Handset Alliance which is lead by Google. Android uses a special virtual machine, e.g. the Dalvik Virtual Machine. Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files. Android applications are packed into an .apk (Android Package) file by the program "aapt" (Android Asset Packaging Tool) To simplify development Google provides the Android Development Tools (ADT) for Eclipse. The ADT performs automatically the conversion f