topsapps is a reporting platform for mobile developers that automatically downloads and visualizes sales data, App Store reviews, hourly ranks and more

Android Facebook Connect Tutorial

Android Develop ReganEscamilla1 36℃ 0评论

This tutorial is about integrating facebook into your android application. I am going to explain various steps like generating your application signature, registering facebook application, downloading facebook sdk and other steps. Here is an official documentation of facebook integration.

Android Facebook Connect Tutorial

Generating App Signature for Facebook Settings

To create facebook android native app you need to provide your Android application signature in facebook app settings. You can generate your application signature (keyhash) using keytool that comes with java. But to generate signature you need openssl installed on your pc. If you don’t have one download openssl from here and set it in your system environment path.

Open your command prompt (CMD) and run the following command to generate your keyhash. While generating hashkey it should ask you password. Give password as android. If it don’t ask for password your keystore path is incorrect.

keytool -exportcert -alias androiddebugkey -keystore "<path-to-users-directory>/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

check the following command how i generated hashkey on my pc.

keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 
Android Facebook Connect Tutorial

Registering your Facebook Application

After generating your app signature successfully, register your facebook application by going to create new facebook application and fill out all the information needed. And select Native Android App and give your hashkey there which you generated previously using keytool.

Android Facebook Connect Tutorial

and note down your facebook App ID

Android Facebook Connect Tutorial

Creating Facebook Reference Project

Once you are done with registering your facebook application, you need to download facebook SDK and create a new reference project. This reference project will be used to compile your actual project.

1. Download facebook android SDK from git repositories.
(git clone git://github.com/facebook/facebook-android-sdk.git)

2. In your Eclipse goto File ⇒ Import ⇒ Existing Projects into Workspace and select the facebook project you downloaded from git repository.

Android Facebook Connect Tutorial

Creating Your Facebook Connect Project

1. Create new Project in your Eclipse IDE. File ⇒ New ⇒ Android Project and fill out all the details.

2. Now we need to add reference of this project to existing facebook project. Right Click on Project ⇒ Properties ⇒ android ⇒ Click on Add button ⇒ select your facebook project ⇒ Click Apply.

Android Facebook Connect Tutorial
Android Facebook Connect Tutorial
Android Facebook Connect Tutorial

Now our project setup is done. We can start coding our facebook application.

3. Open your AndroidManifest.xml file add network connect permission in order to connect to internet.

<uses-permission android:name="android.permission.INTERNET"/> 
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.facebook.androidhive"     android:versionCode="1"     android:versionName="1.0" >      <uses-sdk android:minSdkVersion="8" />      <application         android:icon="@drawable/ic_launcher"         android:label="@string/app_name" >         <activity             android:label="@string/app_name"             android:name=".AndroidFacebookConnectActivity" >             <intent-filter >                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>      <!-- Connect to Internet Permissions -->     <uses-permission android:name="android.permission.INTERNET"/>  </manifest> 

4. Open Your Main Activity Class and initialize all the variables needed.

 public class AndroidFacebookConnectActivity extends Activity {   // Your Facebook APP ID  private static String APP_ID = "308180782571605"; // Replace your App ID here   // Instance of Facebook Class  private Facebook facebook;  private AsyncFacebookRunner mAsyncRunner;  String FILENAME = "AndroidSSO_data";  private SharedPreferences mPrefs;   @Override  public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.main);    facebook = new Facebook(APP_ID);   mAsyncRunner = new AsyncFacebookRunner(facebook); 

5. I created a simple interface which contains button to login, post to wall, show access tokens and logout for testing purpose.

Login to Facebook Account

I used a button to login into facebook account. In your activity write a click event for Login button click. Inside click event declare a function named loginToFacebook();

Login button click event

btnFbLogin.setOnClickListener(new View.OnClickListener() {  @Override  public void onClick(View v) {    loginToFacebook();   } }); 

and function body for loginToFacebook() function is:

 public void loginToFacebook() {   mPrefs = getPreferences(MODE_PRIVATE);   String access_token = mPrefs.getString("access_token", null);   long expires = mPrefs.getLong("access_expires", 0);    if (access_token != null) {    facebook.setAccessToken(access_token);   }    if (expires != 0) {    facebook.setAccessExpires(expires);   }    if (!facebook.isSessionValid()) {    facebook.authorize(this,      new String[] { "email", "publish_stream" },      new DialogListener() {        @Override       public void onCancel() {        // Function to handle cancel event       }        @Override       public void onComplete(Bundle values) {        // Function to handle complete event        // Edit Preferences and update facebook acess_token        SharedPreferences.Editor editor = mPrefs.edit();        editor.putString("access_token",          facebook.getAccessToken());        editor.putLong("access_expires",          facebook.getAccessExpires());        editor.commit();       }        @Override       public void onError(DialogError error) {        // Function to handle error        }        @Override       public void onFacebookError(FacebookError fberror) {        // Function to handle Facebook errors        }       });   }  } 
Android Facebook Connect Tutorial

Posting Message to Facebook Wall

write a click event for post to wall button and inside click event write a function named postToWall()

btnPostToWall.setOnClickListener(new View.OnClickListener() {  @Override  public void onClick(View v) {   postToWall();  } }); 

and function body for postToWall() function is:

 public void postToWall() {   // post on user's wall.   facebook.dialog(this, "feed", new DialogListener() {     @Override    public void onFacebookError(FacebookError e) {    }     @Override    public void onError(DialogError e) {    }     @Override    public void onComplete(Bundle values) {    }     @Override    public void onCancel() {    }   });   } 
Android Facebook Connect Tutorial
Android Facebook Connect Tutorial

Getting Profile Information from Facebook

To get profile information we need to make an api request to facebook graph API. Following is a function that will make an api request to facebook profile graph api and will get profile information from facebook.

getProfileInformation() 
keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

0

The above function will get json data from facebook. You need to parse the json in order to get individual profile data. If you are not aware of json parsing look at this article. Android JSON Parsing Tutorial.

The sample profile json from facebook will be like this

keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

1

Extending facebook Permissions

If you want user’s other information like checkins, friends list etc., you need to extend facebook permissions while logging in user. Check list of facebook permissions

keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

2

Getting Access Token

Sometimes you might needed users access token for future purpose usage. Following code will give you currently logged in user access token.

keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

3

Logout from your app

When user want to stop using facebook for your app, you can provide logout method to clear app state and invalidate access token. So further you can’t make request to facebook from your app.

keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

4

keytool -exportcert -alias androiddebugkey -keystore "C:/Users/Ravi/.android/debug.keystore" | openssl sha1 -binary | openssl base64 

5

This image is for thumbnail purpose
Android Facebook Connect Tutorial

转载请注明:TopsApps » Android Facebook Connect Tutorial

喜欢 (0)or分享 (0)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址