Code2care : TechZone Apps & Tutorials

Android Facebook SDK 3.6 Tutorial Integration With your App


Facebook Android SDK 3.6 Tutorial


Note :



31st August 2014 Update : Facebook SDK for Android v3.17.2 with major changes. So this tutorial is obsolete.

New tutorials for v3.17 : http://code2care.org/pages/integrating-android-facebook-sdk-v3.17.2-tutorial



On December 10, 2013 Facebook released a new version of Android SDK with some new features and bug fixes,

Lets see whats new with ver 3.6 compared to previous version 3.5.2,

  • A Fix for bug in WebDialogs where the dialog would not display properly for large displays with soft keyboards.
  • Fixed bug where the callback for NewPermissionsRequest was not called.
  • Fixed bug in AuthorizationClient where it can hang on orientation changes.
  • AppEventsLogger is released of Beta.
  • setLimitEventUsage is deprecated.
  • New setSelection methods are added on FriendPickerFragment to allow pre-selection of friends.
  • New example use of setSelection API in Friend Picker Sample.
  • Support for Gradle added.



I had written a Tutorial on how to Integrate Facebook SDK 3.5 with Android Application before. Lately I got few mails to write a new tutorial for the latest Facebook Android SDK upgrade ver 3.6, So without further delays lets see how to do so,



Demo Images :
Working Facebook Android SDK 3.6 Tutorial
Facebook Android SDK 3.6 post on wall

Prerequisites


  • Latest Facebook SDK for Android (3.6).
  • Java v1.6 or later.
  • Eclipse Juno v4.2 or later with a default install and the Android SDK (Better to download Android ADT tool form Android Developer website).
  • Android 2.2 (API 8) components installed in order to use the Facebook SDK.



Step 1:Download the latest Facebook Android SDK facebook-android-sdk-3.6.zip




Step 2: Installing Facebook .apk on Emulator


    If you are testing SDK integration on your Device (mobile phone) having Facebook App installed on it , then you can skip this step,

    Android Emulator is not loaded with Play Store so we need to install the Facebook.apk file using ADB tool.

    Steps to install Facebook APK file on Emulator


  • Open Android Virtual Device (AVD) Manager (In Eclipse Menu under Window > Android Virtual Device Manager)

  • Android Virtual Device Manager Create New AVD
  • Create a new AVD with API level 8, if you already have a AVD, no need to create new

  • Create new AVD Configuration
    Launch the AVD, wait till the Emulator Loads Completely, i.e. the OS loads and Lock Screen appears (or else you may get some unwanted error while installing facebook.apk).
    Launch the AVD

  • Extract the Facebook SDK 3.6 file and locate the facebook.apk file.

    Note down the absolute path for the apk file,

    For me the location is I:\facebook-android-sdk-3.6\facebook-android-sdk-3.6\bin\FBAndroid-3.9.apk
  • Locate FBAndroid-3.9.apk
    Now Locate adb tool,

    My location : I:\ 5. Eclipse\ adt-bundle-windows-x86_64-20130522\ adt-bundle-windows-x86_64-20130522\ sdk\ platform-tools
    Locate adb tool

    Open command prompt and go to location where adb tool is present, and execute the following command,

    adb install I:\facebook-android-sdk-3.6\facebook-android-sdk-3.6.0\
    bin\FBAndroid-3.9.apk


    Note : It may take 15-20 minutes for facebook apk to be installed on the Emulator (patience needed).

    Once this is done you will get a Success message on the Command prompt and you will see Facebook app icon on your AVD.

    Executing ADB Command
    FBAndroid-3.9.apk Successfully Installed
    Facebook App Being Installed on Android AVD

Step 3: Setting up Workspace with Facebook libraries


Important! : Your Facebook SDK files and Workspace should be on the same drive or else you may face issues. So before starting just make sure that they are under the same drive (for me its I:/) Open Workspace,

  • Right Click > Import Existing Projects into Workspace,
  • Package Explorer - Import
    Existing Project into Workspace
  • Locate FacebookSDK Projects and Select Facebook SDK Projects only (deselect all others)

  • Only Select FacebookSDK Project
  • Create a new Android Project for testing, fill in the Application name,Project Name and Package Name, See that the Java Version is 1.6.


  • I have added an fb icon under bin > res > drawable-hdpi and have set it as a ImageView in MainActivity.


  • Step 4: Register your App with Facebook Developers Android App Page


      You need to register your App on Facebook developers site to get an app_id


    Step 5: Configuring FacebookSDK with your App



    • Add app-id to string.xml.

    • Add App-id to string xml

    • Under AndroidManifest.xml > Application Tab > Application Nodes , Add Meta Data with,
        Name : com.facebook.sdk.ApplicationId
        Value : @string/appid

    • Add Meta Data Details

      Add Facebook Activity details,
      • Name : com.facebook.LoginActivity
        Label : @string/app_name
      Add Facebook Activity

    • Add Internet and ACCESS NETWORK STATE Permission under : AndroidManifest.xml > Application Tab > Application Nodes > User Permissions
        android.permission.INTERNET
        android.permission.ACCESS_NETWORK_STATE

    • Internet permission and User Permission
      Internet Permissions

    • Now if you run the program will get Jar mismatch! Fix your dependencies Error, to fix this issue you need to delete android-support-v4.jar under Your Project libs folder and place here the same file from FacebookSDK project's libs file.

    • Resolve Jar mismatch! Fix your dependencies Issue



    Step 6 : Generating Keyhash for your Device


    • Most of us get stuck on this step!. The simplest and quickest way to generate keyhash is add the following code onCreate function.
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
        "com.code2care.facebookSDKTuts", 
        PackageManager.GET_SIGNATURES);
          for (Signature signature : info.signatures) {
           MessageDigest md = MessageDigest.getInstance("SHA");
           md.update(signature.toByteArray());
           System.out.println("KeyHash : "+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
       } catch (NameNotFoundException e) {
     } catch (NoSuchAlgorithmException e) {
    } 
    

    Note : Remember to change the package name accordingly (for me its com.code2care.facebookSDKTuts)
    Once you run the app you will find the keyhash in LogCat,
    Generating Keyhash for Android

    You need to add this keyhash to your facebook developer accounts App details page.


    MainActivity.java Class file

    package com.code2care.facebooksdktuts;
    
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.content.pm.Signature;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.util.Base64;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ImageView;
    import android.widget.Toast;
    import com.facebook.Session;
    import com.facebook.SessionState;
    import com.facebook.UiLifecycleHelper;
    import com.facebook.widget.FacebookDialog;
    public class MainActivity extends Activity {
        String message = "Hello there!";
        private UiLifecycleHelper uiHelper;
        ImageView facebook;
        private Session.StatusCallback callback = new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState state,
                    Exception exception) {
                onSessionStateChange(session, state, exception);
            }
        };
        private void onSessionStateChange(Session session, SessionState state,
                Exception exception) {
            if (state.isOpened()) {
                // System.out.println("Logged in...");
            } else if (state.isClosed()) {
                // System.out.println("Logged out...");
            }
        }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            uiHelper.onActivityResult(requestCode, resultCode, data,
                    new FacebookDialog.Callback() {
                        @Override
                        public void onError(FacebookDialog.PendingCall pendingCall,
                                Exception error, Bundle data) {
                            Log.e("Activity",
                                    String.format("Error: %s", error.toString()));
                        }
                        @Override
                        public void onComplete(
                                FacebookDialog.PendingCall pendingCall, Bundle data) {
                            Log.i("Activity", "Success!");
                        }
                    });
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            uiHelper = new UiLifecycleHelper(this, callback);
            uiHelper.onCreate(savedInstanceState);
            
            
            //Code to get KeyHash value.
            try {
                PackageInfo info = getPackageManager().getPackageInfo(
                        "com.code2care.facebooksdktuts", 
                        PackageManager.GET_SIGNATURES);
                for (Signature signature : info.signatures) {
                    MessageDigest md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
                    System.out.println("KeyHash : "+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
                    }
            } catch (NameNotFoundException e) {
            } catch (NoSuchAlgorithmException e) {
            }
            
            facebook = (ImageView) findViewById(R.id.fbicon);
            facebook.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    facebook();
                }
            });
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        @Override
        protected void onDestroy() {
            uiHelper.onDestroy();
            super.onDestroy();
        }
        @Override
        protected void onResume() {
            super.onResume();
            uiHelper.onResume();
        }
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            uiHelper.onSaveInstanceState(outState);
        }
        @Override
        public void onPause() {
            super.onPause();
            uiHelper.onPause();
        }
        public void facebook() {
            if (!checkNetwork()) {
                Toast.makeText(getApplicationContext(),
                        "No active internet connection ...", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            if (!checkFbInstalled()) {
                Toast.makeText(getApplicationContext(),
                        "Facebook app not installed!..", Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(getApplicationContext(), "Loading...",
                    Toast.LENGTH_SHORT).show();
            if (FacebookDialog.canPresentShareDialog(this,
                    FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
                FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
                        this).setName("FacebookSDKTuts")
                        .setLink("http://code2care.org").setDescription(message)
                        .setPicture("http://code2care.org/buddha.jpg").build();
                uiHelper.trackPendingDialogCall(shareDialog.present());
            } else {
                // System.out.println("Fail Success!");
            }
        }
        private boolean checkNetwork() {
            boolean wifiAvailable = false;
            boolean mobileAvailable = false;
            ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] networkInfo = conManager.getAllNetworkInfo();
            for (NetworkInfo netInfo : networkInfo) {
                if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
                    if (netInfo.isConnected())
                        wifiAvailable = true;
                if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (netInfo.isConnected())
                        mobileAvailable = true;
            }
            return wifiAvailable || mobileAvailable;
        }
        public Boolean checkFbInstalled() {
            PackageManager pm = getPackageManager();
            boolean flag = false;
            try {
                pm.getPackageInfo("com.facebook.katana",
                        PackageManager.GET_ACTIVITIES);
                flag = true;
            } catch (PackageManager.NameNotFoundException e) {
                flag = false;
            }
            return flag;
        }
    }
    



    Thats it!!


    Get the Code on Github


    To make things easy i have uploaded these files on Github.

    https://github.com/code2care/FacebookAndroidSDK3.6Tutorial

    Any queries or comments do write to me at : [email protected]


    Top











    Posts related to android.


    1. Share image and text Twitter using your Android Application Programatically

    2. The Android Virtual Device 'myEmulator' is currently running an emulator and cannot be deleted.

    3. Make Android View Scrollable both Horizontally and Vertically

    4. Can we move apps like WhatsApp, Facebook to external MicroSD card

    5. Parsing Data for android-21 failed unsupported major.minor version 51.0

    6. Android : Prevent App for rotation landscape or portrait

    7. ADT quit unexpectedly error on Mac OSX Android Eclipse SDK

    8. Android-Failed to install apk on device EOF Timeout Error

    9. How to change Android EditText Cursor Color

    10. JavaDocs for Android SDK Eclipse IDE

    11. Two Buttons next to each other in Android Layout

    12. Change Title text for Android Activity using java code

    13. How to add Newline to text in Android TextView

    14. Android : Unable to load VM from snapshot : Mac OS X Error

    15. INVALID FILE NAME: MUST CONTAIN ONLY [a-z0-9_.] Android Eclipse Error

    16. Hide Tittle bar and Navigation bar from android activity

    17. appcompat_v7 errors after updates to API level 21 Material Theme

    18. How to Copy Text to Android Clipboard Programatically ClipboardManager (Both Old and New SDK)

    19. [Solution] Running Android Lint has encountered a problem NullPointerException Error

    20. Remove Trailing zeros BigDecimal Java

        more...

    Posts related to facebookSDK.


    1. FacebookSDK] Unable to resolve target android-8 (Android Facebook SDK error)

    2. Integrating Facebook SDK version 3.5.2 with Android app Tutorial

    3. Android Facebook SDK 3.6 Tutorial Integration With your App

    4. Facebook This Message Contains Blocked Content

    5. Integrating Android Facebook SDK v3.17.2 Tutorial

    6. Facebook App page error : You have specified an App Domain but have not specified a valid integration URL

    7. Facebook android SDK error while Linking the SDK project to your project (red cross against the package)

    8. java.lang.NoClassDefFoundError android.support.v4.content.LocalBroadcastManager Error








    Popular tags
    android
    x 175
    eclipse
    x 29
    notepadplusplus
    x 20
    macosx
    x 14
    sharepoint
    x 14
    html
    x 14
    mac
    x 13
    androidstudio
    x 11




    1000+ C Programs     PHP Tutorial     JSON Tutorial     Swift Tutorial     India Pinocdes     About Us     Privacy Policy


    Code2care © 2012-17