Account Kit for Android

To set up Account Kit in your Android app, follow these steps:

1. Prerequisites

2. Configure the SDK

3. Check for Existing Sessions

4. Initiate a Login flow for SMS

5. Initiate a Login flow for Email

6. Perform Additional Configuration

7. Handle the Activity's Result

8. Provide a Logout Button

9. Access Account Information on the Device


Also see Next Steps for optional customizations you can perform.

For an example project that illustrates how to integrate Account Kit, see Account Kit Samples for Android on GitHub.

1. Prerequisites

Before you begin integrating Account Kit into your app, make sure you have completed the following prerequisites.

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

Already have a Facebook developer account? Skip to the next step.

Create Developer Account

B. Get a Facebook App ID

Account Kit for Android requires a Facebook app ID. Follow the steps in the Getting Started, or to use Quick Start, click the button below.

Quick Start for Android

C. Choose Your App Settings

Choose whether to allow email and SMS login, and choose security settings for your app. For more information on choosing your acesss token setting, see Access Tokens, and for information on choosing your app secret setting, see Using the Graph API.

Choose Your App Settings

2. Configure the SDK

Add your Facebook app ID and your Account Kit client token to the AndroidManifest.xml file. You'll find the Account Kit client token in the Account Kit section of the App Dashboard. The application name will be used in the UI on the login screen.

Add the compile dependency with the latest version of the Account Kit SDK in the build.gradle file:

repositories {
  jcenter()
}

dependencies {
  compile 'com.facebook.android:account-kit-sdk:4.+'
}

Add the following to the application tag of your AndroidManifest.xml

<meta-data android:name="com.facebook.accountkit.ApplicationName"
           android:value="@string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
           android:value="@string/FACEBOOK_APP_ID" />
<meta-data android:name="com.facebook.accountkit.ClientToken"
           android:value="@string/ACCOUNT_KIT_CLIENT_TOKEN" />

<activity
  android:name="com.facebook.accountkit.ui.AccountKitActivity"
  android:theme="@style/AppLoginTheme"
  tools:replace="android:theme"/>

Make sure @style/AppLoginTheme inherits from Theme.AccountKit.

Define the value for FACEBOOK_APP_ID as the Facebook app ID shown at the top of your application dashboard, and the value for ACCOUNT_KIT_CLIENT_TOKEN using the client token found in the Account Kit tab in the App Dashboard.

The AccountKitActivity must be defined here as well, to enable it to start in the app. Set the android:theme attribute here to customize the color scheme of the UI.

If you wish to disable App Events for your Account Kit application, add the following line to AndroidManifest.xml:

<meta-data android:name="com.facebook.accountkit.FacebookAppEventsEnabled"
           android:value="false"/>

By default, this value is true. See App Events and Analytics for more information.

To reduce the size of the SDK, you can specify only the supported languages you need. See Specifying Supported Languages on how to do this.

3. Check for Existing Sessions

If your app will receive the user's access token directly (i.e., the Enable Client Access Token Flow switch in your app's dashboard is ON) then you should check for a valid, existing token:

import com.facebook.accountkit.AccountKit;
import com.facebook.accountkit.AccessToken;

AccessToken accessToken = AccountKit.getCurrentAccessToken();

if (accessToken != null) {
  //Handle Returning User
} else {
  //Handle new or logged out user
}

If your app will receive an authorization code that it will pass to the server (i.e., the Enable Client Access Token Flow switch in your app's dashboard is OFF), it is up to you to have your server communicate the correct login status to your client application.

4. Initiate a Login flow for SMS

import com.facebook.accountkit.AccountKit;

public static int APP_REQUEST_CODE = 99;

public void phoneLogin(final View view) {
  final Intent intent = new Intent(getActivity(), AccountKitActivity.class);
  AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
    new AccountKitConfiguration.AccountKitConfigurationBuilder(
      LoginType.PHONE,
      AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN
  // ... perform additional configuration ...
  intent.putExtra(
    AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
    configurationBuilder.build());
  startActivityForResult(intent, APP_REQUEST_CODE);
}

The APP_REQUEST_CODE is your custom code to track your login flow. It can be any integer, but it needs to be set by your application.

When initializing your intent extras, be sure to specify the AccountKitActivity.ResponseType that matches your application's authorization setting in the Facebook developer portal dashboard: TOKEN if the Enable Client Access Token Flow switch in your app's dashboard is ON, and CODE if it is OFF.

If people are logged into their Facebook account on their Android devices, and have a verified phone number, Account Kit verifies them without requiring them to enter the SMS code. For more information, see Instant Verification.

5. Initiate a Login flow for Email

import com.facebook.accountkit.AccountKit;

public static int APP_REQUEST_CODE = 99;

public void emailLogin(final View view) {
  final Intent intent = new Intent(getActivity(), AccountKitActivity.class);
  AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
    new AccountKitConfiguration.AccountKitConfigurationBuilder(
      LoginType.EMAIL,
      AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN
  // ... perform additional configuration ...
  intent.putExtra(
    AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
    configurationBuilder.build());
  startActivityForResult(intent, APP_REQUEST_CODE);
}

The APP_REQUEST_CODE is your custom code to track your login flow. It can be any integer, but it needs to be set by your application.

When initializing your intent extras, be sure to specify the AccountKitActivity.ResponseType that matches your application's authorization setting in the Facebook developer portal dashboard: TOKEN if the Enable Client Access Token Flow switch in your app's dashboard is ON, and CODE if it is OFF.

With Account Kit email login, people receive an email sent to their account. When they click on the link in the email on the same device that your app is installed on, they return to your app to finish the login activity.

To return people to your app, add the AccountKitEmailRedirectActivity activity with the following intent filter to your AndroidManifest.xml file:

 <activity android:name="com.facebook.accountkit.ui.AccountKitEmailRedirectActivity">
   <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/ak_login_protocol_scheme" />
  </intent-filter>
</activity>

And the following in your strings.xml file:

// if your Facebook App ID is 1234567, you should use ak1234567
<string name="ak_login_protocol_scheme">akFACEBOOK_APP_ID</string>

6. Perform Additional Configuration

The AccountKitConfigurationBuilder object offers multiple UI and behavior customization points for your use of Account Kit via methods that allow you to override default properties at runtime.

MethodDescription

setInitialAuthState(String initialAuthState)

(Optional) A developer-generated nonce used to verify that the received response matches the request. Fill this with a random value at runtime; when the login call returns, check that the corresponding param in the response matches the one you set in this method.

setInitialEmail(String initialEmail)

(Optional) Pre-fill the user's email address in the email login flow.

Note: By default, the email field provides a dropdown list of the user's email addresses if the GET_ACCOUNTS permission is granted.

setDefaultCountryCode(String defaultCountryCode)

(Optional) Set the default country code shown in the SMS login flow.

setInitialPhoneNumber(PhoneNumber initialPhoneNumber)

(Optional) Pre-fill the user's phone number in the SMS login flow.

setFacebookNotificationsEnabled(boolean facebookNotificationsEnabled)

(Optional) If this flag is set, Account Kit offers the user the option to receive their confirmation message via a Facebook notification in the event of an SMS failure, if their phone number is associated with their Facebook account. The associated phone number must be the primary phone number for that Facebook account.

Default: true

setTitleType(AccountKitActivity.TitleType titleType)

(Optional) Set to AccountKitActivity.TitleType.APP_NAME to use your application's name as the title for the login screen, or AccountKitActivity.TitleType.LOGIN to use a localized translation of "Login" as the title.

Default: AccountKitActivity.TitleType.LOGIN

setTheme(int theme)

(Optional) Pass in a resource identifier for a theme to have that theme used for the login screen. See Customizing the UI for Android for more information.

Note: If you specify both a theme and an Advanced UI Manager object (see below), the Advanced UI Manager will take precedence and overwrite theme elements.

setAdvancedUIManager(AdvancedUIManager advancedUIManager)

(Optional) Pass in an object that implements the AdvancedUIManager protocol. See Customizing the UI for Android for more information.

setReadPhoneStateEnabled(boolean readPhoneStateEnabled)

(Optional) If the READ_PHONE_STATE permission is granted and this flag is true, the app will pre-fill the user's phone number in the SMS login flow. Set to false if you wish to use the READ_PHONE_STATE permission yourself, but you do not want the user's phone number pre-filled by Account Kit.

Default: true

setReceiveSMS(boolean receiveSMSEnabled)

(Optional) If the RECEIVE_SMS permission is granted and this flag is true, the app will automatically read the Account Kit confirmation SMS and pre-fill the confirmation code in the SMS login flow. Set to false if you wish to use the RECEIVE_SMS permission yourself, but you do not want the SMS confirmation code pre-filled by Account Kit.

Default: true

setSMSWhitelist(String[] smsWhitelist)

(Optional) Use this to specify a list of permitted country codes for use in the SMS login flow. The value is an array of short country codes as defined by ISO 3166-1 Alpha 2. To restrict availability to just the US (+1) and The Netherlands (+31), pass in ["US", "NL"].

setSMSBlacklist(String[] smsBlacklist)

(Optional) Use this to specify a list of country codes to exclude during the SMS login flow. Only the country codes in the blacklist are unavailable. People can still use the rest of Account Kit's supported country codes. If a country code appears in both the whitelist and the blacklist, the blacklist takes precedence and the country code is not available. Just like the whitelist, the value is an array of short country codes as defined by ISO 3166-1 Alpha 2.

When you whitelist and blacklist country codes, you can use the following combinations of lists with the described results.

Lists Result

No whitelist or blacklist

All country codes supported by Account Kit are available.

Whilelist

Only country codes in the whitelist are available.

Blacklist

All country codes supported by Account Kit except those in the blacklist are available.

Whitelist and blacklist

Only the country codes in the whitelist that are not also in the blacklist are available. Note that the blacklist takes priority for codes that that are in both lists.

7. Handle the Activity's Result

Capture the Account Kit activity's result and extract the AccountKitLoginResult from the Intent argument to determine the status of the login attempt.

@Override
protected void onActivityResult(
        final int requestCode,
        final int resultCode,
        final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == APP_REQUEST_CODE) { // confirm that this response matches your request
        AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
        String toastMessage;
        if (loginResult.getError() != null) {
            toastMessage = loginResult.getError().getErrorType().getMessage();
            showErrorActivity(loginResult.getError());
        } else if (loginResult.wasCancelled()) {
            toastMessage = "Login Cancelled";
        } else {
            if (loginResult.getAccessToken() != null) {
                toastMessage = "Success:" + loginResult.getAccessToken().getAccountId();
            } else {
                toastMessage = String.format(
                        "Success:%s...",
                        loginResult.getAuthorizationCode().substring(0,10));
            }

            // If you have an authorization code, retrieve it from
            // loginResult.getAuthorizationCode()
            // and pass it to your server and exchange it for an access token.

            // Success! Start your next activity...
            goToMyLoggedInActivity();
        }

        // Surface the result to your user in an appropriate way.
        Toast.makeText(
                this,
                toastMessage,
                Toast.LENGTH_LONG)
                .show();
    }
}

8. Provide a Logout Button

If you began the login session with AccountKitActivity.ResponseType.TOKEN, a logout option is available to remove the stored AccessToken from the device.

import com.facebook.accountkit.AccountKit;

AccountKit.logOut();

9. Access Account Information on the Device

If your began the login session with AccountKitActivity.ResponseType.TOKEN, it's possible to access the Account Kit ID, phone number and email of the current account via a call to getCurrentAccount().

AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
  @Override
  public void onSuccess(final Account account) {
    // Get Account Kit ID
    String accountKitId = account.getId();

    // Get phone number
    PhoneNumber phoneNumber = account.getPhoneNumber();
    String phoneNumberString = phoneNumber.toString();

    // Get email
    String email = account.getEmail();
  }
  
  @Override
  public void onError(final AccountKitError error) {
    // Handle Error
  }
});