Monday, January 21, 2013

Getting Started with the Facebook SDK for Android


The Facebook SDK for Android is the easiest way to integrate your Android app with Facebook's platform. The SDK provides support for Login with Facebook authentication, reading and writing to Facebook's APIs, as well as support for UI elements such as pickers and dialogs.
To get started developing with the Facebook SDK for Android, follow the steps below. Although the screenshots in this guide are from an Apple OS X environment, the steps for installing on a Windows machine are almost identical, and any differences in the instructions are highlighted.



1 Install the Prerequisites
You need Eclipse, the Android SDK, and the ADT Plugin
Eclipse is the most popular choice for developing Android apps. 'Eclipse Classic', found on the downloads page, is sufficient for Android development. This guide assumes you are using v4.2 (Juno) or later, with a default install. You also need Java v1.6 or later.
Once you have Eclipse, download the Android SDK, available from the Android Developers site, and install it as described.
Also make sure you continue those instructions to install the Android Developer Tools (ADT) Plugin. You may be asked to restart Eclipse to complete the installation.
You'll need to have the Android 2.2 (API 8) components installed in order to use the Facebook SDK.
You should now see two new icons in your Eclipse toolbar, and entries in its 'Window' menu, to launch the Android SDK Manager and AVD Manager (for device emulators) respectively:
Even if you have a real Android device to develop with, it is very useful to have an Android emulator configured. In the newly-installed 'AVD Manager', create a new AVD, and leave simple, default settings for it:
You can now start the emulator either directly from the AVD Manager tool, or later, at the time when you run your first Android project in Eclipse.
2 Install the Facebook SDK for Android and the Facebook APK
Download and extract the installation package. Install the Facebook app to your emulator
Download and extract the SDK ZIP file. The resulting folder, facebook-android-sdk-3.0, contains the SDK itself. Note the location of this folder.
The Facebook SDK uses Facebook's native app to provide support for authentication when it's present. On a real device, you can simply install this app for free from Google Play to test this out. However, it's not possible to access Google Play on an emulator, so if you want to test the flow there, we include an copy in the SDK that you can install.
The installable APK of the Facebook app is in the bin folder of the SDK, and named FBAndroid-2.0.apk or similar. To install it onto an Android emulator, you'll first need to start the emulator.
Secondly, locate the adb tool in the platform-tools directory of your main Android SDK. On OS X, you will have chosen this location when you unzipped the Android SDK. On Windows, the SDK is installed into your home directory, under AppData\Local\Android\android-sdk
Assuming you've placed the Facebook SDK in your home directory, you use adb to install the APK to the running emulator in OS X like this:
./adb install ~/facebook-android-sdk-3.0/bin/FBAndroid-2.0.apk
And on Windows, like this:
adb install %HOMEPATH%\facebook-android-sdk-3.0\bin\FBAndroid-2.0.apk
Once complete, check the apps screen of the emulator to check that the app has been installed correctly. If you need to force the upgrade of this app from a previous version, add the -r flag, like this on OS X:
./adb install -r ~/facebook-android-sdk-3.0/bin/FBAndroid-2.0.apk
You should now see the Facebook app in the emulator's app list or homescreen.
If you choose not to install this APK to your emulator, you can still develop with the Facebook SDK, but your app's Facebook authentication will fall back to taking place via a web view, rather than with the smoother app switching flow.
3 Import the SDK into Eclipse
Add the SDK as a library project to your workspace, along with the sample projects
The installation folder contains a directory called facebook, which is the SDK project itself. There is also a selection of sample projects in the samples folder.
You can import all of these projects into a clean workspace in one go. In particular, ensure there is no existing facebook project in your workspace. If one exists, it is possibly referencing an older Facebook SDK. You should either delete it or change your workspace.
To import the SDK library project and the samples, with the new SDK, go to Eclipse's 'File' > 'Import' menu, and select 'General' / 'Existing Projects into Workspace':
Browse to select the root of your SDK folder, facebook-android-sdk-3.0. You should see the SDK appear in the list as 'FacebookSDK', along with all of the samples.
You must unselect the 'Copy projects into workspace' option so that each of the sample projects retains a correct reference to the neighboring SDK. However, this means that Eclipse creates a link to the project in the SDK installation, rather than a copy of it.
(This is useful if you expect to update the SDK in-place in the future and have your workspace's library project update accordingly. However, if you choose to edit the SDK samples in the future, you may wish to subsequently re-import them with a copy so as not to affect the original versions.)
Click 'Finish'. If the sample projects are showing errors, simply use 'Project' > 'Clean' in Eclipse to refresh all the project's states.
It is also possible that your Eclipse compiler level has not matched that required by Android. If you see errors like "Android requires compiler compliance level 5.0 or 6.0.", simply make sure the project (or Eclipse) properties mandate v1.6 in the Java Compiler section:
You are now ready to run the sample apps. You may need to provide your Android key hash to Facebook to run some of the samples. You can learn how to do this in the next step.

4 Run the Samples
Try the sample projects, and add your Android key hash to your Facebook profile
Each of the samples demonstrates an important part of the SDK and techniques for building social apps.
The following samples are available in the SDK:
Basic samples
  • ProfilePictureSample: demonstrates non-logged-in usage of the profile picture control
  • FriendPickerSample: demonstrates usage of the native friend picker to choose amongst the user's friends
  • PlacePickerSample: demonstrates logged-in usage of the place picker control
Feature samples
  • SessionLoginSample: demonstrates detailed login flow using the SDK
  • JustRequestSample: demonstrates logged-in user making single and batched Facebook API requests
  • BooleanOGSample: demonstrates publishing an Open Graph custom action type
  • SwitchUserSample: demonstrates an approach to allow switching between multiple users
Complete samples
  • HelloFacebookSample: an all-round sample that demonstrates profile access, status updates and photo uploading
  • Scrumptious: demonstrates the use of login, requests, pickers, picture uploads, and Open Graph publishing
  • Hackbook: another sample app demonstrating a selection of Graph API calls. Note that this sample is untouched from v2.0 of the SDK, and demonsrates the SDK's backward-compatibility.
The samples should be visible in your workspace following the import in the previous step, and each should correctly reference the neighboring 'FacebookSDK' library project.
Select a sample project and press 'Run' in Eclipse. When you first try to do so, you may be prompted to indicate how to do so:
Select 'Android Application', and your Android emulator should start, displaying the sample you've chosen.
The very simplest apps, such as ProfilePictureSample, will run immediately. If you want to run those that involve authentication, however, you will need to perform one extra step of configuration, which is to provide your Android key hash to Facebook.
Put simply, every Android app you'll create will be signed, and you will need to register each app's key hash with Facebook as a security check for authenticity - as we'll see later. But to bypass this check for the SDK samples and to get them up and running quickly, you can add your key hash to your global Facebook Developer profile.
Firstly, to generate your key hash on your local computer, run Java's keytool utility (which should be on your console's path) against the Android debug keystore. This is, by default, in your home .android directory). On OS X, run:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | 
 openssl sha1 -binary | openssl base64
On Windows, use:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.
keystore | openssl sha1 -binary | openssl base64
You will be prompted for a password. This should be 'android' without quotes. You'll then be given a key hash of 30 characters or so. (If you are not prompted for a password, something is wrong and you must check your paths above to ensure the debug.keystore is present.)
Finally go to the Facebook Developer site. Make sure you are logged into Facebook and, using the dropdown menu in the top-right, go to your 'Settings':
Then, go to the 'Developer Settings' section on the left. If you haven't done so yet, you will be required to quickly register as a developer.
You'll then be able to add and save your key hash into your profile:
(Note that you can add multiple key hashes here if you are developing with multiple machines.)
You will now be able to compile and run all of the authentication-based samples on your emulator without issue.

Troubleshooting
If you have a problem running the sample app, it may be related to the key hash. If this is the case, one of the following scenarios will occur:
  • A native Login Dialog is displayed but after accepting the permissions you are still in a logged out state. The logcat also contains an exception similar to this:
    12-20 10:23:24.507: W/fb4a:fb:OrcaServiceQueue(504): 
    com.facebook.orca.protocol.base.ApiException: remote_app_id does not match 
    stored id
  • A non-native Login Dialog is displayed that includes an error message at the top: ''..App is Misconfigured for facebook login...''.
Besides double checking your key hash generation steps, here is another option that ensures you're using the correct key hash. It involves changing code in one of the sample apps to print the signature sent to Facebook. You'll modify the 'HelloFacebookSample' sample.
Open up the HelloFacebookSampleActivity class and make the following temporary change to the onCreate() method:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

    } catch (NoSuchAlgorithmException e) {

    }

    ...
Save your changes and re-run the sample. Check your logcat output for a message similar to this:
12-20 10:47:37.747: D/KeyHash:(936): 478uEnKQV+fMQT8Dy4AKvHkYibo=
Save the printed key hash in your developer profile. Re-run the samples once more and verify that you can log in successfully.

5 Create a Facebook App
Create a new Facebook app, get its ID and associate your Android key hash with it
Return to the App Dashboard on the Facebook Developers site. Click 'Create New App', and enter basic information such as its name and a unique namespace.
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.
Alternatively, you can, of course, use the ID of an existing app.
In either case, you will also need to associate your Android key hash with the app. Click 'Edit App' and open up the 'Native Android App' section at the bottom of the dashboard. Add the key hash that you obtained at the end of the previous step with the keytool app.
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.

6 Create a new Android Project with Facebook Login

Create a new project, link to the Facebook SDK; demonstrate Facebook Login and fetch the user's name
In this final step, we will create a new project and add the minimum code required to demonstrate Facebook login.
Create a new Android project
Create a new Android Application Project in Eclipse, using 'File' > 'New' > 'Project...' and select 'Android Application Project':
You are not obliged to use the same app name and namespace as you did when you registered the app with Facebook, but we have here, for consistency. You can then quickly choose an icon for your app:
Next, we can create the main activity for the app. For this example, we have a very basic user-interface, and can simply choose a 'BlankActivity':
Finally, provide a name for the activity. You can leave this as the default MainActivity with a layout name of activity_main.
Finish the wizard, and your new project will have been created, along with the main activity class:

Register the package and activity with Facebook
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 the Android settings. Also enable 'Facebook Login':

Link to the SDK project and configure the Facebook app ID
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"/>)
A minimum viable social application
When we initially created this project, a simple user-interface layout was created, called activity_main.xml and in the res/layout folder of your project. Open this, select the text label in the middle of the screen of the designer, and give it an ID of @+id/welcome, as shown below:
If you view the source for the layout, you should see something like
...
<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    ...
With this reference, we will be able to update the welcome to include the user's name when they log in with Facebook. To do so, we finally open the MainActivity.java file in the project's src folder.
The first thing we should do is add a couple of imports to the top of the class file for the Facebook SDK (and the model package which includes a number of strongly-typed social graph objects):
import com.facebook.*;
import com.facebook.model.*;
You will also need the following Android packages, the first of which allows us to work with the text field we created an id for earlier:
import android.widget.TextView;
import android.content.Intent;
An important part of the Facebook SDK is the Session class which manages much of the process of authenticating and authorizing users. Since the login flow for your app will require the users to transition out of, and back into, this Activity, we need a small amount of wiring to update the active session:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
(More comprehensive implementations of the Session and Activity life cycles are used in the sample apps, and described in the Facebook Login guide. For example, you will want to benefit from caching tokens, resuming sessions and the like.)
At the end of the onCreate method, add Session.openActiveSession() to initiate the Facebook Login. This takes three arguments: a reference to this Activity, a flag to indicate that the Login UI should be used, and finally a callback for when the status changes. (A more robust implementation might need to create this callback as a named instance, but for this simple example, we can keep it anonymous).
@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) {

    }
  });
}
The call method of the callback will likely fire multiple times (when the session is OPENING and then OPENED, for example). We want to use that final successful state to fetch the user's name and update the welcome message. Inside the call method, check that the session is open:
if (session.isOpened()) {
}
Inside this, we can make a request to the /me endpoint of the Facebook Graph API to fetch the user's basic information. The Request class provides a number of convenience methods for creating and executing common calls like this, including the static executeMeRequestAsync. This takes a reference to the session, and, in turn, another callback (strongly-typed for the user data that will be returned) which will contain your code for when the API call completes:
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

  // callback after Graph API response with user object
  @Override
  public void onCompleted(GraphUser user, Response response) {
  }
});
Inside this onCompleted method, we simply replace the TextView label (which we gave the 'welcome' ID to, earlier) with the user's name:
if (user != null) {
  TextView welcome = (TextView) findViewById(R.id.welcome);
  welcome.setText("Hello " + user.getName() + "!");
}
Save all your files, and run. On launch, the application will immediately initiate the Facebook Login flow (which will either be via the Facebook app if you installed the APK on the emulator, or via a modal web view dialog if not), and and on successful login, will display the user's name:
Congratulations! You have built your first social Android app and are ready to deep dive and further explore the Facebook SDK.
To conclude, our completed code for MainActivity.java is as follows:
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.executeMeRequestAsync(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() + "!");
              }
            }
          });
        }
      }
    });
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      Session.getActiveSession().onActivityResult(this, requestCode, resultCode, 
 data);
 
  }

}
7 Start Coding!
That's it... now go and enhance one of the sample apps, work through the Scrumptious Tutorial, and get creative.
Source:Facebook.

No comments:

Post a Comment