Facebook Integration In Android

facebook_ad_update_logo-2

In the following tutorial we will learn how to login using facebook, share links, images and use like view.

Login at https://developers.facebook.com/ and create a new application as follows:

Screen Shot 2015-08-17 at 8.42.28 pm

Screen Shot 2015-08-17 at 8.44.21 pm

Screen Shot 2015-08-17 at 8.47.41 pm

After creating application on facebook developers website, we will create a new project in android studio with a blank activity.

And add following to build.gradle inside project:

repositories {
        mavenCentral()
    }

Screen Shot 2015-08-18 at 2.59.40 am

After that we will add facebook sdk to our project by adding following dependency to build.gradle inside app folder like this:

Screen Shot 2015-08-18 at 3.01.08 am

After the facebook sdk is added we can see that a facebook folder is added in the project structure.

Note*: Don’t forget to sync the gradle everytime the gradle is updated.

Now we will configure our application settings:

Screen Shot 2015-08-18 at 2

 

Add your email in the provided space. For generating keyhash we will add the following code in our onCreate of MainActivity.java

try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "fbdemo.androidbeasts.com.facebookdemo",
                    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 (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }

We will run the above code once and use the keyhash shown in the logcat of android studio. We will add the keyhash generated in the settings page as shown in above image.

Now we will turn on the live features for our application on facebook developers website as shown in below image:

Screen Shot 2015-08-18 at 5.11.38 am

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity">

<com.facebook.login.widget.LoginButton 
android:id="@+id/login_button" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerInParent="true" />

</RelativeLayout>

MainActivity.java

package fbdemo.androidbeasts.com.facebookdemo;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;



public class MainActivity extends AppCompatActivity {
    LoginButton loginButton;
    CallbackManager callbackManager;
    AccessTokenTracker accessTokenTracker;
    AccessToken accessToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        setContentView(R.layout.activity_main);
        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("public_profile", "user_friends");
        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(
                    AccessToken oldAccessToken,
                    AccessToken currentAccessToken) {
                // Set the access token using
                // currentAccessToken when it's loaded or set.
                accessToken = currentAccessToken;
            }
        };


        // If the access token is available already assign it.
        accessToken = AccessToken.getCurrentAccessToken();
        // If using in a fragment
        //loginButton.setFragment(MainActivity.this);

        // Other app specific specialization

        //generate keyhash
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "fbdemo.androidbeasts.com.facebookdemo",
                    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 (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                Toast.makeText(getApplicationContext(), "Login success", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(MainActivity.this, SharingActivity.class));

            }

            @Override
            public void onCancel() {
                // App code
                Toast.makeText(getApplicationContext(),"Login cancelled",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Toast.makeText(getApplicationContext(),exception.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
        //In case we are not using login button
       /* LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Toast.makeText(getApplicationContext(),"Login success",Toast.LENGTH_SHORT).show();
                        // App code
                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(getApplicationContext(),"Login cancelled",Toast.LENGTH_SHORT).show();
                        // App code
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Toast.makeText(getApplicationContext(),exception.getMessage(),Toast.LENGTH_SHORT).show();
                        // App code
                    }
                });*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

strings.xml

<resources>
    <string name="app_name">FacebookDemo</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="facebook_app_id">FACEBOOK_APP_ID</string>
    <string name="title_activity_sharing">SharingActivity</string>

<!-- TODO: Remove or change this placeholder text -->
    <string name="hello_blank_fragment">Hello blank fragment</string>
</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="fbdemo.androidbeasts.com.facebookdemo" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:largeHeap="true">
        <activity android:name=".MainActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<!-- Please note here that in com.facebook.app.FacebookContentProvider1234 , 1234 is the Facebook App Id you have to write it like this-->
        <provider android:name="com.facebook.FacebookContentProvider" android:authorities="com.facebook.app.FacebookContentProvider1234" android:exported="true" />

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />

        <activity android:name=".SharingActivity" android:label="@string/title_activity_sharing" >
        </activity>
    </application>

</manifest>


Screen Shot 2015-08-18 at 5.37.20 am

Sharing Links, Images and using facebook LikeView:

activity_sharing.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" 
tools:context="fbdemo.androidbeasts.com.facebookdemo.SharingActivity">

<Button android:id="@+id/shareLink" 
android:layout_width="fill_parent" 
android:layout_height="60dp" 
android:text="Share Link on Facebook" 
android:textAllCaps="false" 
android:textSize="20sp" 
android:layout_centerHorizontal="true"/>

<Button android:id="@+id/shareImage" 
android:layout_width="fill_parent" 
android:layout_height="60dp" 
android:layout_marginTop="20dp" 
android:layout_below="@+id/shareLink" 
android:text="Share Image on Facebook" 
android:textAllCaps="false" 
android:textSize="20sp" 
android:layout_centerHorizontal="true"/>

<com.facebook.share.widget.LikeView 
android:id="@+id/like_view" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_below="@+id/shareImage" 
android:layout_marginTop="20dp" />

</RelativeLayout>

SharingActivity.java

package fbdemo.androidbeasts.com.facebookdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.facebook.share.widget.LikeView;
import com.facebook.share.widget.ShareDialog;


public class SharingActivity extends AppCompatActivity {
    Button shareButton,shareImage;
    ShareDialog shareDialog;
    CallbackManager callbackManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        setContentView(R.layout.activity_sharing);
        shareDialog = new ShareDialog(this);
        // this part is optional

        shareButton=(Button) findViewById(R.id.shareLink);
        shareImage=(Button) findViewById(R.id.shareImage);
        
        shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        Toast.makeText(getApplicationContext(), "Successfully shared", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(getApplicationContext(), "Sharing cancelled", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(FacebookException e) {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ShareDialog.canShow(ShareLinkContent.class)) {
                    ShareLinkContent linkContent = new ShareLinkContent.Builder()
                            .setContentUrl(Uri.parse("https://androidbeasts.wordpress.com"))
                            .setContentTitle("Demo Facebook App")
                            .setImageUrl(Uri.parse("YOUR_IMAGE_URL"))
                            .setContentDescription("This is a facebook demo application for testing purpose.")
                            .build();
                    shareDialog.show(linkContent);
                }
            }
        });

        shareImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ShareDialog.canShow(SharePhotoContent.class)) {
                    Bitmap image = returnBitmap(SharingActivity.this);
                    SharePhoto photo = new SharePhoto.Builder()
                            .setBitmap(image)
                            .build();
                    SharePhotoContent content = new SharePhotoContent.Builder()
                            .addPhoto(photo)
                            .build();
                    shareDialog.show(content);
                }
            }
        });


        LikeView likeView = (LikeView) findViewById(R.id.like_view);
        likeView.setObjectIdAndType(
                "https://www.facebook.com/pages/Android-Beasts/1438667233127168",
                LikeView.ObjectType.PAGE);
    }
public Bitmap returnBitmap(Context context){
    //You can also use other sources for bitmap.
    Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
            R.drawable.androids);
    return icon;
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_sharing, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Screenshot_2015-08-18-02-36-32SharingActivity

Screenshot_2015-08-18-01-51-26Sharing Link 

Screenshot_2015-08-18-02-09-11Sharing Image

Screenshot_2015-08-18-02-36-02Using Facebook LikeView

DOWNLOAD FULL CODE

2 thoughts on “Facebook Integration In Android

  1. Birat Bade Shrestha

    When I click the shareImage button nothing shows.I am having this problem for a week now.
    Status can be share but not photos.I have mentioned the content provider in the manifest.xml.
    Can you help please.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s