Wednesday, May 14, 2014

Android Facebook Integration Tutorial

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:
  1. Facebook SDK
  2. Intent Share

Integrating Facebook SDK

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

Generating application signature

You have to generate a key signature , but before you generate it, make sure you have SSL installed , otherwise you have to download SSl. It can be downloaded here.
Now open command prompt and redirect to your java jre folder. Once you reach there, type this command exactly. You have to replace the path in the inverted commas with your keystore path which you can found in ecclipse by selecting the window tab and selecting the preferences tab and then selectng the build option under android from left side.
keytool -exportcert -alias androiddebugkey -keystore "your path" | openssl sha1 -binary | openssl base64
Once you enter it , you will be prompt for password. Give android as the password and then copy the key that is given to you. It is shown in the image below:
Android Facebook Tutorial

Registering your application

Now create a new facebook application at developers.facebook.com/apps and fill all the information. It is shown below:
Android Facebook Tutorial Now move to the native android app section and fill in your project and class name and paste the hash that you copied in step 1. It is shown below:
Android Facebook Tutorial If everything works fine, you will receive an application ID with the secret. Just copy the application id and save it somewhere. It is shown in the image below:
Android Facebook Tutorial

Downloading SDK and integrating it

Download facebook sdk here. Import this into ecclipse. Once imported , right click on your facebook project and click on properties.Click on android, click on add button and select facebook sdk as the project.Click ok.

Creating facebook login application

Once everything is complete , you can run the samples, that comes with SDK or create your own application. In order to login, you need to call openActiveSession method and implements its callback. Its syntax is given below:
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {

   // callback when session changes state
   public void call(Session session, SessionState state, Exception exception)   
   {
      if (session.isOpened()) {
      // make request to;2 the /me API
         Request.executeMeRequestAsync(session, new Request.
         GraphUserCallback() {

            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user, Response response) {
            if (user != null) {
               TextView welcome = (TextView) findViewById(R.id.welcome);
               welcome.setText("Hello " + user.getName() + "!");
              }
            }
       });
   }
}

Intent share

Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the facebook application handles it. We will simply call the facebook application and pass the data to share. This way, we can share something on facebook.
Android provides intent library to share data between activities and applications. In order to use it as share intent , we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is given below:
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));
Apart from the these methods , there are other methods available that allows intent handling. They are listed below:
Sr.NoMethod & description
1addCategory(String category)
This method add a new category to the intent.
2createChooser(Intent target, CharSequence title)
Convenience function for creating a ACTION_CHOOSER Intent
3getAction()
This method retrieve the general action to be performed, such as ACTION_VIEW
4getCategories()
This method return the set of all categories in the intent.nt and the current scaling event
5putExtra(String name, int value)
This method add extended data to the intent.
6toString()
This method returns a string containing a concise, human-readable description of this object

Example

Here is an example demonstrating the use of IntentShare to share data on facebook. It creates a basic application that allows you to share some text on facebook.
To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as IntentShare under a package com.example.intentshare. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components.
4Modify the res/values/string.xml to add necessary string components.
5Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modifed main activity file src/com.example.intentshare/MainActivity.java.
package com.example.intentshare;

import java.io.File;
import java.io.FileOutputStream;

import com.example.intentshare.R;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private ImageView img;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      img = (ImageView) findViewById(R.id.imageView1);

   }

   @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;
   }
   public void open(View view){
      Intent shareIntent = new Intent();
      shareIntent.setAction(Intent.ACTION_SEND);
      shareIntent.setType("text/plain");
      shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint");
      startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));

   }

}
Following is the modified content of the xml res/layout/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" >

   <ImageView
      android:id="@+id/imageView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="98dp"
      android:layout_marginTop="139dp"
      android:onClick="open"
      android:src="@drawable/tp" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp"
      android:text="@string/tap"
      android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">IntentShare</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="tap">Tap the button to share something</string>

</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.intentshare"
   android:versionCode="1"
   android:versionName="1.0" >

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

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.intentshare.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>
   </application>

</manifest>
Let's try to run your IntentShare application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Android facebook Tutorial Select your mobile device as an option and then check your mobile device which will display your default screen:
Android facebook Tutorial Now just tap on the image logo and you will see a list of share providers.
Android facebook Tutorial Now just select facebook from that list and then write any message. It is shown in the image below:
Android facebook Tutorial

No comments:

Post a Comment