Android Facebook Integration: Android - LeaVe my baThRoom at-least !

Android Facebook Integration

Android Facebook Integration
Android allow applications to connect with Facebook. So we can perform authentication and share data or any kind of updates on Facebook.This blog is about integrating Facebook into your android application. It is very easy to integrate Facebook in android application.

There are two ways through which we can integrate and share something on Facebook through android application:-

1. Facebook SDK
2. Intent Share

Integrating Facebook SDK

The Facebook SDK for Android is the easiest way to integrate your Android app with Facebook.
It enables:
  • Facebook Login - Authenticate people with their Facebook credentials.
  • Account Kit - Log people in with just their phone number or email address.
  • Share and Send dialog - Enable sharing content from your app to Facebook.
  • App Events - Log events in your application.
  • Graph API - Read and write to the Graph API.

Steps are listed below 

Generate key Hash Value
Now you need to Get Key Hash Value for your machine. The key hash value is used by Facebook as security check for login. To get key hash value of your machine, write following code in onCreate() method of MainActivity.java
  • try
  • {
  • PackageInfo info = getPackageManager().getPackageInfo( getPackageName(),
    • 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) {
    • }

After you are done downloading, please import it in Android Studio.
Create Facebook App
We need to create facebook app in order to get Facebook App ID. To do so, create an application on FB developer site. Go to https://developers.facebook.com After login, click on Add a New App. Type your application name.
create facebook app
Follow the setup
generate app id
Add Facebook SDK to Your Project

To use Facebook SDK in a project, add it as a build dependency and import it. If you are starting a new project, follow all the steps below. To add Facebook SDK to an existing project, start with step 3.
1. Go to Android Studio | New Project | Minimum SDK
2. Select "API 15: Android 4.0.3" or higher and create your new project.
3. In your project, open
your_app | Gradle Scripts | build.gradle
4. Add the Maven Central Repository to build.gradle before dependencies:
repositories {
        mavenCentral()
    }
5. Add compile 'com.facebook.android:facebook-android-sdk:[4,5)' to your build.gradle dependencies.
6. Build your project.
7. Import Facebook SDK into your app:
import com.facebook.FacebookSdk;

Add Facebook App ID
Add your Facebook App ID to your app and update your Android manifest.
1. Open your strings.xml file, for example: /app/src/main/res/values/strings.xml.
2. Add a new string with the name facebook_app_id containing the value of your Facebook App ID:
3. Open AndroidManifest.xml.
4. Add a uses-permission element to the manifest:
5. Add a meta-data element to the application element:
    ...
   <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id">
    ...
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 −
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

An android share intent allow your app to share contents such as URL or text and Image to other apps installed in your Android device like Facebook, Twitter, Messaging, Instagram, whatsapp, etc.
 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, " From Suven Consultency");
startActivity(Intent.createChooser(shareIntent, "Hello!!!!"));
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.
  • You will use Android studio to create an Android application under a package net.suven.android.android_facebookintegration.
  • Modify src/MainActivity.java file to add necessary code.
  • Modify the res/layout/activity_main to add respective XML components.
  • Run the application and choose a running android device and install the application on it and verify the results.
MainActivity.java File
package net.suven.android.android_facebookintegration;
 
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
import java.io.FileNotFoundException;
import java.io.InputStream;
 
public class MainActivity extends AppCompatActivity {
private ImageView img;
 
protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
 
       img=(ImageView)findViewById(R.id.imageView);
       Button b1=(Button)findViewById(R.id.button);
 
       b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
       Intent sharingIntent = new Intent(Intent.ACTION_SEND);
       Uri screenshotUri = Uri.parse("android.resource://net.suven.android.android_facebookintegration/*");
 
       try {
       InputStream stream = getContentResolver().openInputStream(screenshotUri);
       } catch (FileNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       }
       sharingIntent.setType("image/jpeg");
       sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
       startActivity(Intent.createChooser(sharingIntent, "Share image using"));
       }
       });
       }
       }

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<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"
   tools:context=".MainActivity">
 
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/textView"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:textSize="30dp"
       android:text="Share On Facebook " >
 
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="SCTPL"
       android:id="@+id/textView2"
       android:layout_below="@+id/textView"
       android:layout_centerHorizontal="true"
       android:textSize="35dp"
       android:textColor="#ff16ff01" >
 
   <ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/imageView"
       android:layout_below="@+id/textView2"
       android:layout_centerHorizontal="true"
       android:src="@drawable/suvenlogo"
   >
 
   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Share"
       android:id="@+id/button"
       android:layout_marginTop="61dp"
       android:layout_below="@+id/imageView"
       android:layout_centerHorizontal="true" >
</RelativeLayout>
Following is the output of application.
After launching application it will display following screen. 
Android facebook integration home
Click on share button. you will see list of share provider
share post

Now select Facebook from the list and then write your message shown in following image 

Comments

  1. Thank you ! Nice content....
    helped me a lot
    will you make a same informative blog on linked-in integration?
    Thank you in advance....

    ReplyDelete

Post a Comment

Popular posts from this blog

How E-commerce Sites can Increase Sales with Pinterest?

Every thing U can do with a Link-List + Programming_it_in_JaVa

Test Your SQL Basics - Part_1