Wednesday, September 19, 2012

Using Facebook SDK in Android development

,
Part I:
SDK Version: 
M3
fbConnecting to Facebook from an Android application is not as easy, as it looks. This guide will help you through some problems that you will propably encounter, with a clear and simple solution.
1. Step
First of all, download the official Facebook SDK from this site: https://github.com/facebook/facebook-android-sdk/
After that, create an application in this http://www.facebook.com/developers/ site, to get an APP ID.
2. Step
You need to create the key hash value of your signature and your android debugkeystore (for the develop stage), and than add them to your Facebook Application, in the application site. (Edit Settings -> Mobile and Devices section)
To do this, we need Openssl, download from: http://code.google.com/p/openssl-for-windows/downloads/list, and extract to a folder (in my case, c:\openssl).
To create this hash values, you need to navigate to your JAVA jdk folder, where the keytool.exe is. (In my case, in windows is: c:\Program Files(x86)\Java\jdk 1.6.0_24\bin)
Copy your debug.keystore to there from the (in my case) c:\Users\MyUserName\.android folder. In the jdk/bin folder, open a command prompt, and execute the following:
keytool -exportcert -alias androiddebugkey -keystore debug.keystore > c:\openssl\bin\debug.txt
Prompt1
(Use your openssl folder, and hit enter when asking password)
Navigate to the openssl/bin folder, and we have a debug.txt here, which contains the keystore values, but not in the expected format! Open a command promt from there, and execute the following commands:

  1. openssl sha1 -binary debug.txt > debug_sha.txt
  2. openssl base64 -in debug_sha.txt > debug_base64.txt
Prompt2
And now we are DONE! The debug_base64.txt contains the hash value, we need to copy it to the application site, in the Mobile and Devices section.
AddHash
You need to do the this hash creating flow with your signature too, to make working apk-s!
3. Step
Finally we can start coding... In the next part!



Part II: 

In this part, I show you an android application, which logging in to Facebook, then get the Facebook ID.
Please go through the first part of the tutorial, before reading this post.
1. Step
Create a new Android project in Eclipse, choose "create project from existing source", and set the location to: "Your Facebook SDK"\facebook. In my case it's D:\facebook android sdk\facebook.
sdk
2. Step
Create a new empty Android project, and open project properties/android. Hit Add in the Library section, add the facebook project.
sdk
3. Step
Change the main.xml like this:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <TextView android:layout_width="fill_parent" android:id="@+id/textFacebook"
  6.                 android:gravity="center_horizontal" android:layout_height="wrap_content"
  7.                 android:text="@string/welcome" android:layout_alignParentTop="true" />
  8.         <Button android:text="@string/enter" android:id="@+id/buttonLogin"
  9.                 android:layout_below="@+id/textFacebook"
  10.                 android:layout_centerHorizontal="true" android:layout_width="wrap_content"
  11.                 android:layout_height="wrap_content" android:layout_marginTop="30dip"></Button>
  12.         <ProgressBar android:id="@+id/progressLogin"
  13.                 android:layout_centerInParent="true" android:layout_width="wrap_content"
  14.                 android:visibility="gone" android:layout_height="wrap_content"></ProgressBar>
  15. </RelativeLayout>
And add Internet Permission to the AndroidManifest.xml:

  1.         <uses-permission android:name="android.permission.INTERNET">
  2.         </uses-permission>
My strings.xml looks like this:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.     <string name="welcome">Welcome </string>
  4.     <string name="app_name">FacebookTest</string>
  5.     <string name="enter">Log in to Facebook</string>
  6. </resources>
3. Step
Create an abstract class, for the Facebook connection. Don't forget to insert your app id!

  1. public abstract class FBConnectionActivity extends Activity {
  2.         public static final String TAG = "FACEBOOK";
  3.         private Facebook mFacebook;
  4.         public static final String APP_ID = "INSERT YOUR APP ID";
  5.         private AsyncFacebookRunner mAsyncRunner;
  6.         private static final String[] PERMS = new String[] { "read_stream" };
  7.         private SharedPreferences sharedPrefs;
  8.         private Context mContext;
  9.  
  10.         private TextView username;
  11.         private ProgressBar pb;
  12.  
  13.         public void setConnection() {
  14.                 mContext = this;
  15.                 mFacebook = new Facebook(APP_ID);
  16.                 mAsyncRunner = new AsyncFacebookRunner(mFacebook);
  17.         }
  18.  
  19.         public void getID(TextView txtUserName, ProgressBar progbar) {
  20.                 username = txtUserName;
  21.                 pb = progbar;
  22.                 if (isSession()) {
  23.                         Log.d(TAG, "sessionValid");
  24.                         mAsyncRunner.request("me", new IDRequestListener());
  25.                 } else {
  26.                         // no logged in, so relogin
  27.                         Log.d(TAG, "sessionNOTValid, relogin");
  28.                         mFacebook.authorize(this, PERMS, new LoginDialogListener());
  29.                 }
  30.         }
  31.  
  32.         public boolean isSession() {
  33.                 sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
  34.                 String access_token = sharedPrefs.getString("access_token", "x");
  35.                 Long expires = sharedPrefs.getLong("access_expires", -1);
  36.                 Log.d(TAG, access_token);
  37.  
  38.                 if (access_token != null && expires != -1) {
  39.                         mFacebook.setAccessToken(access_token);
  40.                         mFacebook.setAccessExpires(expires);
  41.                 }
  42.                 return mFacebook.isSessionValid();
  43.         }
  44.  
  45.         private class LoginDialogListener implements DialogListener {
  46.  
  47.                 @Override
  48.                 public void onComplete(Bundle values) {
  49.                         Log.d(TAG, "LoginONComplete");
  50.                         String token = mFacebook.getAccessToken();
  51.                         long token_expires = mFacebook.getAccessExpires();
  52.                         Log.d(TAG, "AccessToken: " + token);
  53.                         Log.d(TAG, "AccessExpires: " + token_expires);
  54.                         sharedPrefs = PreferenceManager
  55.                                         .getDefaultSharedPreferences(mContext);
  56.                         sharedPrefs.edit().putLong("access_expires", token_expires)
  57.                                         .commit();
  58.                         sharedPrefs.edit().putString("access_token", token).commit();
  59.                         mAsyncRunner.request("me", new IDRequestListener());
  60.                 }
  61.  
  62.                 @Override
  63.                 public void onFacebookError(FacebookError e) {
  64.                         Log.d(TAG, "FacebookError: " + e.getMessage());
  65.                 }
  66.  
  67.                 @Override
  68.                 public void onError(DialogError e) {
  69.                         Log.d(TAG, "Error: " + e.getMessage());
  70.                 }
  71.  
  72.                 @Override
  73.                 public void onCancel() {
  74.                         Log.d(TAG, "OnCancel");
  75.                 }
  76.         }
  77.  
  78.         private class IDRequestListener implements RequestListener {
  79.  
  80.                 @Override
  81.                 public void onComplete(String response, Object state) {
  82.                         try {
  83.                                 Log.d(TAG, "IDRequestONComplete";);
  84.                                 Log.d(TAG, "Response: " + response.toString());
  85.                                 JSONObject json = Util.parseJson(response);
  86.  
  87.                                 final String id = json.getString("id");
  88.                                 final String name = json.getString("name");
  89.                                 FBConnectionActivity.this.runOnUiThread(new Runnable() {
  90.                                         public void run() {
  91.                                                 username.setText("Welcome: " + name+"\n ID: "+id);
  92.                                                 pb.setVisibility(ProgressBar.GONE);
  93.  
  94.                                         }
  95.                                 });
  96.                         } catch (JSONException e) {
  97.                                 Log.d(TAG, "JSONException: " + e.getMessage());
  98.                         } catch (FacebookError e) {
  99.                                 Log.d(TAG, "FacebookError: " + e.getMessage());
  100.                         }
  101.                 }
  102.  
  103.                 @Override
  104.                 public void onIOException(IOException e, Object state) {
  105.                         Log.d(TAG, "IOException: " + e.getMessage());
  106.                 }
  107.  
  108.                 @Override
  109.                 public void onFileNotFoundException(FileNotFoundException e,
  110.                                 Object state) {
  111.                         Log.d(TAG, "FileNotFoundException: " + e.getMessage());
  112.                 }
  113.  
  114.                 @Override
  115.                 public void onMalformedURLException(MalformedURLException e,
  116.                                 Object state) {
  117.                         Log.d(TAG, "MalformedURLException: " + e.getMessage());
  118.                 }
  119.  
  120.                 @Override
  121.                 public void onFacebookError(FacebookError e, Object state) {
  122.                         Log.d(TAG, "FacebookError: " + e.getMessage());
  123.                 }
  124.  
  125.         }
  126.  
  127.         @Override
  128.         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  129.                 mFacebook.authorizeCallback(requestCode, resultCode, data);
  130.         }
  131. }
4. Step
Add the connection activity to the manifest:

  1. <activity android:name=".FBConnectionActivity&quot; android:label="@string/app_name"></activity>
5. Step
Change the Main activity like that:

  1. public class Main extends FBConnectionActivity {
  2.         private TextView txtUserName;
  3.         private ProgressBar pbLogin;
  4.         private Button btnLogin;
  5.        
  6.     @Override
  7.     public void onCreate(Bundle savedInstanceState) {
  8.         super.onCreate(savedInstanceState);
  9.         setContentView(R.layout.main);
  10.        
  11.         txtUserName = (TextView) findViewById(R.id.textFacebook);
  12.         pbLogin = (ProgressBar) findViewById(R.id.progressLogin);
  13.         btnLogin = (Button) findViewById(R.id.buttonLogin);
  14.                 btnLogin.setOnClickListener(new OnClickListener() {
  15.                         @Override
  16.                         public void onClick(View arg0) {
  17.                                 pbLogin.setVisibility(ProgressBar.VISIBLE);
  18.                                 setConnection();
  19.                                 getID(txtUserName, pbLogin);
  20.                         }
  21.                 });
  22.     }
  23. }
And see the result:
sdk

(helloandroid)

0 comments to “Using Facebook SDK in Android development”

Post a Comment

 

Android Development Tutorials Copyright © 2011 -- Template created by O Pregador -- Powered by Blogger Templates