Facebook Login for Android

The Facebook SDK for Android enables people to sign into your app with Facebook Login. When people log into your app with Facebook they can grant permissions to your app so you can retrieve information or perform actions on Facebook on their behalf.

When you develop your app with version 4.14.0 of the Facebook SDK for Android, Facebook Login has automatic integration with Facebook Lite. If people don't have the Facebook Android app installed, Facebook Login uses Facebook Lite instead to display the login screen and get credentials. Previous SDKs required that people have the Facebook app installed.

To read more about Facebook login, see Login Portal. To read about use cases and features, see Overview. For information on permissions, see Managing Permissions, Android and Permissions with Facebook Login.

Implement Facebook Login with the following steps:

1. Prerequisites

2. Add the Facebook Login Button

3. Register a Callback to Handle the Login Result

4. Enable Chrome Custom Tabs

5. Check Login Status


Also see Next Steps for advanced topics.

1. Prerequisites

Before you begin implementing Facebook Login, make sure you have completed the following setup.

A. Download the Facebook App

Download the Facebook app by clicking the button below.

Download Facebook for Android

B. Create a Developer Account

If you don't have a Facebook developer account, create one by clicking the button below. Your Facebook developer account gives you access to developer tools and allows you to create Facebook apps.

Create Developer Account

C. Download the Android SDK

Download the latest Facebook SDK for Android.

Download Android SDK

D. Get a Facebook App ID, Include the SDK, and Add Key Hashes to Your Profile

Use Quick Start by clicking the button below, or follow the steps in the Getting Started.

Quick Start for Android

E. Enable Single Sign On for Your App

Enable single sign on for your app by choosing your app from My Apps on the Facebook Developer site, choosing Settings for your app, and setting Single Sign On to Yes.

F. Include FacebookActivity in your AndroidManifest.xml.

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

2. Add the Facebook Login Button

The simplest way to add Facebook Login to your app is to add LoginButton from the SDK. This is a custom view implementation of a Button. You can use this button in your app to implement Facebook Login.

In conjunction with the LoginButton, you use the following classes, available in the SDK:

  • LoginManager - Initiates the login process with the requested read or publish permissions.
  • CallbackManager - Use to route calls back to the Facebook SDK and your registered callbacks. You should call it from the initiating activity or fragments onActivityResult call.
  • AccessToken: - Use this class Graph API requests. It shows the user id, and the accepted and denied permissions.
  • Profile - This class has basic information about person logged in.

The LoginButton is a UI element that wraps functionality available in the LoginManager. So when someone clicks on the button, the login is initiated with the permissions set in the LoginManager. The button follows the login state, and displays the correct text based on someone's authentication state.

To add the Facebook Login button, first add it to your layout XML file with the full class name, com.facebook.widget.LoginButton:

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

Then set up the button in your UI by adding it to a fragment and update your activity to use your fragment.

You can customize the properties of Login button and register a callback in your onCreateView() method.

Properties you can customize includes LoginBehavior, DefaultAudience, ToolTipPopup.Style and permissions on the LoginButton. For example:

@Override
public View onCreateView(
        LayoutInflater inflater,
        ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.splash, container, false);

    loginButton = (LoginButton) view.findViewById(R.id.login_button);
    loginButton.setReadPermissions("email");
    // If using in a fragment
    loginButton.setFragment(this);    
    // Other app specific specialization

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
        }

        @Override
        public void onCancel() {
            // App code
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
        }
    });    
}

If you use the LoginButton in a fragment, you need to set the fragment on the button as shown by calling setFragment.

You then need to call FacebookSdk.sdkInitialize to initialize the SDK, and then call CallbackManager.Factory.create to create a callback manager to handle login responses. Here's an example of adding the callback in a fragment:

public class MainActivity extends FragmentActivity {
    CallbackManager callbackManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.usersettings_fragment_login_button);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { ... });
    }

Finally you should call callbackManager.onActivityResult to pass the login results to the LoginManager via callbackManager.

3. Register a Callback

To respond to a login result, you need to register a callback with either LoginManager or LoginButton. If you register the callback with LoginButton, don't need to register the callback on Login manager.

You add the callback to your activity or fragment's onCreate() method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());

    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    // App code
                }

                @Override
                public void onCancel() {
                     // App code
                }

                @Override
                public void onError(FacebookException exception) {
                     // App code   
                }
    });
}

If login succeeds, the LoginResult parameter has the new AccessToken, and the most recently granted or declined permissions.

You don't need a registerCallback for login to succeed, you can choose to follow current access token changes with the AccessTokenTracker class described below.

Then in onActivityResult() forward the login results to the callbackManager created in onCreate():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}

Every activity and fragment that you integrate with the FacebookSDK Login or Share should forward onActivityResult to the callbackManager

4. Enable Chrome Custom Tabs

Enable Chrome Custom Tabs by adding an intent filter to your manifest and a fb_login_protocol_scheme to your strings.xml file. When you enable Chrome Custom Tabs, the SDK presents the login dialog in a Chrome Custom Tab instead of a WebView when the Facebook app is not installed. As a result, people do not have to enter their credentials again if they are already logged into Facebook in their Chrome browser.

Add the following intent filter to your AndroidManifest.xml file:

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

Add the following in your strings.xml file:

// if your App ID is 1234567, you should use fb1234567
<string name="fb_login_protocol_scheme">fbAPP_ID</string>

5. Check Login Status

Your app can only have one person at a time logged in, and LoginManager sets the current AccessToken and Profile for that person. The FacebookSDK saves this data in shared preferences and sets it during SDK initialization. You can see if a person is already logged in by checking AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile().

Get Current Token

You can load AccessToken.getCurrentAccessToken with the SDK from cache or from an app book mark when your app cold launches. You should check its validity at your Activity's onCreate method:

public class MainActivity extends FragmentActivity {
    CallbackManager callbackManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {...});
    }

Then you can later perform the actual login, such as in a custom button's OnClickListener:

 LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"));

Finally, in the onActivityResult in your Activity, pass the result to the CallbackManager:

@Override
 protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}