Friday, October 24, 2014

Setting up Facebook SDK on Android Studio

  1. Download the Facebook SDK from https://developers.facebook.com/docs/android/ and unzip the archive
  2. In Android Studio, choose "Import Module" from the File menu.
  3. In the wizard, set the source path of the module to import as the "facebook" directory inside your extracted folder. 
  4. Now you might see a gradle build error, something along the lines of :  Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'. 
  5. To fix this problem, open the gradle.properties file [which is present in the root folder of your app] and add the following lines:  

        ANDROID_BUILD_TARGET_SDK_VERSION=19
        ANDROID_BUILD_TOOLS_VERSION=20.0.0
        ANDROID_BUILD_SDK_VERSION=19
        ANDROID_BUILD_MIN_SDK_VERSION=11

  6.  The above properties will vary based on you app's build sdk version, target, etc.
  7.  Now you should be set. Just follow the instruction on Facebook's SDK page for setting up a fb app,        authentication, etc.

  8. One other thing you might have to do while registering your app on Facebook would be to get the         key hash of your app. For that add this function to your main activity and call it from onCreate()
    public static String printKeyHash(Activity context) {
        PackageInfo packageInfo;
        String key = null;
        try {

            //getting application package name, as defined in manifest
            String packageName = context.getApplicationContext().getPackageName();

            //Retriving package info
            packageInfo = context.getPackageManager().getPackageInfo(packageName,
                    PackageManager.GET_SIGNATURES);

            Log.e("Package Name=", context.getApplicationContext().getPackageName());

            for (Signature signature : packageInfo.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                key = new String(Base64.encode(md.digest(), 0));

                // String key = new String(Base64.encodeBytes(md.digest()));
                Log.e("Key Hash=", key);

            }
        } catch (PackageManager.NameNotFoundException e1) {
            Log.e("Name not found", e1.toString());
        }

        catch (NoSuchAlgorithmException e) {
            Log.e("No such an algorithm", e.toString());
        } catch (Exception e) {
            Log.e("Exception", e.toString());
        }

        return key;
    }