Friday 3 May 2013

Facebook integration in android

Introduction:
This tutorial describes how to integrate an Android application with Facebook. We are going to publish a wall post on Facebook from an Android application. We will be using the Facebook Android SDK to do this.
Xml Layout:

In the onCreate method we are restoring the previously stored credentials – if any – from the SharedPreferences of the app. As we will see later, these will be set after succesful authentication.
In the onCreate method we are also setting the view to the following layout xml file:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="250dp"
    android:layout_height="125dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:padding="5dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="5dp"
            android:text="Do you want to share this on Facebook?" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/FacebookShareButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_margin="2dp"
            android:onClick="share"
            android:padding="5dp"
            android:text="Yes" />

        <Button
            android:id="@+id/FacebookShareNotButton"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_margin="2dp"
            android:onClick="doNotShare"
            android:padding="5dp"
            android:text="No" />
    </LinearLayout>

</RelativeLayout>


AndroidManifest.xml file:

  <activity
            android:name=".ShareOnFacebook"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Dialog" >
        </activity>


MainActivity:
here is context for set String and send it to ShareOnfacebookclass for sharing.


      Intent postOnFacebookWallIntent = new Intent(this, ShareOnFacebook.class);
      postOnFacebookWallIntent.putExtra("facebookMessage""Here is String  which            
      you want post..");
      startActivity(postOnFacebookWallIntent);


ShareOnFacebook activity:

public class ShareOnFacebook extends Activity{

      private static final String APP_ID = "";
      private static final String[] PERMISSIONS = new String[] {"publish_stream"};

      private static final String TOKEN = "access_token";
      private static final String EXPIRES = "expires_in";
      private static final String KEY = "facebook-credentials";

      private Facebook facebook;
      private String messageToPost;

      public boolean saveCredentials(Facebook facebook) {
            Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
            editor.putString(TOKEN, facebook.getAccessToken());
            editor.putLong(EXPIRES, facebook.getAccessExpires());
            return editor.commit();
      }

      public boolean restoreCredentials(Facebook facebook) {
            SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
            facebook.setAccessToken(sharedPreferences.getString(TOKENnull));
            facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
            return facebook.isSessionValid();
      }

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            facebook = new Facebook(APP_ID);
            restoreCredentials(facebook);

            requestWindowFeature(Window.FEATURE_NO_TITLE);

            setContentView(R.layout.facebook_dialog);

            String facebookMessage = getIntent().getStringExtra("facebookMessage");
            if (facebookMessage == null){
                  facebookMessage = "Test wall post";
            }
            messageToPost = facebookMessage;
      }

      public void doNotShare(View button){
            finish();
      }
      public void share(View button){
            if (! facebook.isSessionValid()) {
                  loginAndPostToWall();
            }
            else {
                  postToWall(messageToPost);
            }
      }

      public void loginAndPostToWall(){
            facebook.authorize(thisPERMISSIONS, Facebook.FORCE_DIALOG_AUTH, newLoginDialogListener());
      }

      public void postToWall(String message){
            Bundle parameters = new Bundle();
            parameters.putString("message", message);
            parameters.putString("description""topic share");
            try {
                  facebook.request("me");
                  String response = facebook.request("me/feed", parameters, "POST");
                  Log.d("Tests""got response: " + response);
                  if (response == null || response.equals("") ||
                              response.equals("false")) {
                        showToast("Blank response.");
                  }
                  else {
                        showToast("Message posted to your facebook wall!");
                  }
                  finish();
            } catch (Exception e) {
                  showToast("Failed to post to wall!");
                  e.printStackTrace();
                  finish();
            }
      }

      class LoginDialogListener implements DialogListener {
            public void onComplete(Bundle values) {
                  saveCredentials(facebook);
                  if (messageToPost != null){
                        postToWall(messageToPost);
                  }
            }
            public void onFacebookError(FacebookError error) {
                  showToast("Authentication with Facebook failed!");
                  finish();
            }
            public void onError(DialogError error) {
                  showToast("Authentication with Facebook failed!");
                  finish();
            }
            public void onCancel() {
                  showToast("Authentication with Facebook cancelled!");
                  finish();
            }
      }

      private void showToast(String message){
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
      }
}


More Reference link:
http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
http://androiddevelopement.blogspot.in/2011/06/facebook-integration-in-your-android.html
http://www.integratingstuff.com/2010/10/14/integrating-facebook-into-an-android-application/

No comments:

Post a Comment