Custom Facebook Integration

Android allows your application to connect to facebook and share data or any kind of updates on facebook. This chapter is about integrating facebook into your application.

There are two ways through which you can integrate facebook and share something from your application. These ways are listed below −

  • Facebook SDK
  • Intent Share

Integrating Facebook SDK

This is the first way of connecting with facebook. You have to register your application and then receive some Application Id , and then you have to download the facebook SDK and add it to your project. The steps are listed below:

Step: 1

Step: 2

Step: 3

Step: 4

1. MainActivity.java

package com.tutorialsee;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

public class MainActivity extends Activity {

ArrayList<HashMap<String, String>> array, array1, arraylist;
Context context;
static String msg = "",error = "";
String userid = "", name = "";
String flg = "L";
static ImageView loginfb;
@SuppressWarnings("unused")
private static String APP_ID = "551519815013101";
@SuppressWarnings("unused")
private ProfileTracker mProfileTracker;
private CallbackManager callbackManager;
private LoginManager manager;
public SharedPreferences mPrefs;
String pid = "0";
RelativeLayout rl;
String FILENAME = "AndroidSSO_data";
AccessToken accessToken;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
PrefernceSettings.openDataBase(this);
FacebookSdk.sdkInitialize(MainActivity.this.getApplicationContext());
loginfb = (ImageView) findViewById(R.id.loginfb);
loginfb.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
onClickPostStatusUpdate();
}
});

//Key Hash
/* try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.tutorialsee",
                    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 (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }*/



}

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

private void onClickPostStatusUpdate() {
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("public_profile", "email");
manager = LoginManager.getInstance();
manager.logInWithReadPermissions(this, permissionNeeds);
manager.registerCallback(callbackManager,new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {

@Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// TODO Auto-generated method stub
String email = object.optString("email");
PrefernceSettings.setFBEMAIL(email);
String name = object.optString("name");
PrefernceSettings.setUserName(name);
SentDataFacebook();

}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}

@Override
public void onCancel() {
System.out.println("onCancel");
}


@Override
public void onError(FacebookException error) {
// TODO Auto-generated method stub
System.out.println("onError");
}
});
}

protected void SentDataFacebook() {
if (BaseActivity.isNetworkConnected(context)) {
SentDataFacebook msp = new SentDataFacebook();
msp.execute();
} else {
Toast toast = Toast.makeText(getApplicationContext(),"Please check your internet connection", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
class SentDataFacebook extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
BaseActivity.loader(context);
}

@Override
protected String doInBackground(String... params) {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email",PrefernceSettings.getFBEMAIL()));
nameValuePairs.add(new BasicNameValuePair("username",PrefernceSettings.getUserName()));
String res = BaseActivity.getJson(nameValuePairs, getApplicationContext(),Constant.SOCIALLOGIN);
try {
JSONObject jObject = new JSONObject(res);
msg = jObject.getString("success");
if (MainActivity.msg.trim().equals("success")) {
userid = jObject.getString("user_id");
} else {
userid = jObject.getString("user_id");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
BaseActivity.unloader(context);
if (msg.trim().equals("true")) {


Intent i = new Intent(MainActivity.this, Login.class);
startActivity(i);

} else {
if (msg.trim().equals("User Exist")) {
Intent i = new Intent(MainActivity.this, Login.class);
startActivity(i);


} else {
Toast toast = Toast.makeText(context,"Please check your Username or password",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
}
}

2. activity_main.xml

<LinearLayout 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:background="#00BCD4"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/busdstton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@drawable/logo"
        android:gravity="center"
        android:src="@drawable/logo" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/loginfb"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:contentDescription="@drawable/facebooklarg"
            android:src="@drawable/facebooklarg" />
    </LinearLayout>

</LinearLayout>

3. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorialsee"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SET_DEBUG_APP" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <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=".Login"
            android:label="@string/title_activity_login" >
        </activity>
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

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

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider551519815013101"
            android:exported="true" />
    </application>

</manifest>