How To Use Facebook Integration in android

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.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.tutorialsee.R;
import com.facebook.android.FacebookError;

public class AndroidFacebookConnectActivity extends Activity {

private static String APP_ID = "551519815013101"; // Replace with your App ID
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
ImageView btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnFbLogin = (ImageView) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
mAsyncRunner = new AsyncFacebookRunner(facebook);

btnFbLogin.setOnClickListener(new View.OnClickListener() {

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

//Getting facebook Profile info
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getProfileInformation();
}
});

//Posting to Facebook Wall
btnPostToWall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postToWall();
}
});

//Showing Access Tokens
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAccessTokens();
}
});
}

//Function to login into facebook
public void loginToFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);

if (access_token != null) {
facebook.setAccessToken(access_token);
btnFbLogin.setVisibility(View.INVISIBLE);
btnFbGetProfile.setVisibility(View.VISIBLE);
btnPostToWall.setVisibility(View.VISIBLE);
btnShowAccessTokens.setVisibility(View.VISIBLE);
}

if (expires != 0) {
facebook.setAccessExpires(expires);
}

if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {

@Override
public void onCancel() {
}

@Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",facebook.getAccessToken());
editor.putLong("access_expires",facebook.getAccessExpires());
editor.commit();

btnFbLogin.setVisibility(View.INVISIBLE);
btnFbGetProfile.setVisibility(View.VISIBLE);
btnPostToWall.setVisibility(View.VISIBLE);
btnShowAccessTokens.setVisibility(View.VISIBLE);
}

@Override
public void onError(DialogError error) {
}

@Override
public void onFacebookError(FacebookError fberror) {
}

});
}
}

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


//Get Profile information
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("id");
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nid: " + email, Toast.LENGTH_LONG).show();
}

});


} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

//post to facebook wall
public void postToWall() {
facebook.dialog(this, "feed", new DialogListener() {

@Override
public void onFacebookError(FacebookError e) {
}

@Override
public void onError(DialogError e) {
}

@Override
public void onComplete(Bundle values) {
}

@Override
public void onCancel() {
}
});

}

//show Access Tokens
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}

//Logout user from Facebook
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
@Override
public void onComplete(String response, Object state) {
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {

@Override
public void run() {
btnFbLogin.setVisibility(View.VISIBLE);
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
}
});
}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}

2. main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_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"
        android:visibility="visible" />

    <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/btn_fblogin"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:contentDescription="@drawable/facebooklarg"
            android:src="@drawable/facebooklarg"
            android:visibility="visible" />
    </LinearLayout>

    <!-- Facebook Post to Wall Button -->

    <Button
        android:id="@+id/btn_fb_post_to_wall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dip"
        android:background="@drawable/btnround"
        android:textColor="#F8F8F8"
        android:padding="10dp"
        android:text="@string/aa"
        android:visibility="gone" />
    <!-- Facebook Logout Button -->

    <Button
        android:id="@+id/btn_get_profile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dip"
        android:background="@drawable/btnround"
        android:textColor="#F8F8F8"
        android:padding="10dp"
        android:src="@drawable/btn_logout"
        android:text="@string/bb"
        android:visibility="gone" />

    <!-- Button to show access tokens -->

    <Button
        android:id="@+id/btn_show_access_tokens"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dip"
        android:background="@drawable/btnround"
        android:textColor="#F8F8F8"
        android:padding="10dp"
        android:text="@string/cc"
        android:visibility="gone" />

</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="23"/>
     <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" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name="com.tutorialsee.AndroidFacebookConnectActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
    </application>
</manifest>