Working example of latest android facebook sdk login

41,724

Solution 1

First of all install latest sdk and do something like this:

Under ~\FaceBook-Sdk\facebook-android-sdk-3.5.2\samples.

You will find the samples of whatever you have posted. But may be It will not work. So what you have to do to make it run is:

Make application on Facebook side. Get your fb_api_key from there and put in the project you get from samples.

Solution 2

See this example, it is using Latest Facebook SDK and cover basic login + sharing.

Now do the following changes to your application manifest file. Put the following code before tag. Make sure you are using your own AppID obtained from Facebook developer console.

<activity android:name="com.facebook.LoginActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/app_id" />

Your Activity Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="20dp" >

    <com.facebook.widget.LoginButton
        android:id="@+id/fb_login_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        facebook:confirm_logout="false"
        facebook:fetch_user_info="true" />

    <TextView
        android:id="@+id/user_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:textSize="18sp" />

    <Button
        android:id="@+id/update_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/update_status" />

    <Button
        android:id="@+id/post_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/post_image" />

</LinearLayout>

Activity Java class

package com.domain.yourapp;

import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;

public class FBActivity extends FragmentActivity {

    private LoginButton loginBtn;
    private Button postImageBtn;
    private Button updateStatusBtn;

    private TextView userName;

    private UiLifecycleHelper uiHelper;

    private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");

    private static String message = "Sample status posted from android app";

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

        uiHelper = new UiLifecycleHelper(this, statusCallback);
        uiHelper.onCreate(savedInstanceState);

        setContentView(R.layout.activity_facebook);

        userName = (TextView) findViewById(R.id.user_name);
        loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
        loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
                if (user != null) {
                    userName.setText("Hello, " + user.getName());
                } else {
                    userName.setText("You are not logged");
                }
            }
        });

        postImageBtn = (Button) findViewById(R.id.post_image);
        postImageBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                postImage();
            }
        });

        updateStatusBtn = (Button) findViewById(R.id.update_status);
        updateStatusBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });

        buttonsEnabled(false);
    }

    private Session.StatusCallback statusCallback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (state.isOpened()) {
                buttonsEnabled(true);
                Log.d("FacebookSampleActivity", "Facebook session opened");
            } else if (state.isClosed()) {
                buttonsEnabled(false);
                Log.d("FacebookSampleActivity", "Facebook session closed");
            }
        }
    };

    public void buttonsEnabled(boolean isEnabled) {
        postImageBtn.setEnabled(isEnabled);
        updateStatusBtn.setEnabled(isEnabled);
    }

    public void postImage() {
        if (checkPermissions()) {
            Bitmap img = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_launcher);
            Request uploadRequest = Request.newUploadPhotoRequest(
                    Session.getActiveSession(), img, new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            Toast.makeText(FBActivity.this,
                                    "Photo uploaded successfully",
                                    Toast.LENGTH_LONG).show();
                        }
                    });
            uploadRequest.executeAsync();
        } else {
            requestPermissions();
        }
    }

    public void postStatusMessage() {
        if (checkPermissions()) {
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            if (response.getError() == null)
                                Toast.makeText(FBActivity.this,
                                        "Status updated successfully",
                                        Toast.LENGTH_LONG).show();
                        }
                    });
            request.executeAsync();
        } else {
            requestPermissions();
        }
    }

    public boolean checkPermissions() {
        Session s = Session.getActiveSession();
        if (s != null) {
            return s.getPermissions().contains("publish_actions");
        } else
            return false;
    }

    public void requestPermissions() {
        Session s = Session.getActiveSession();
        if (s != null)
            s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                    this, PERMISSIONS));
    }

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
        buttonsEnabled(Session.getActiveSession().isOpened());
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

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

    @Override
    public void onSaveInstanceState(Bundle savedState) {
        super.onSaveInstanceState(savedState);
        uiHelper.onSaveInstanceState(savedState);
    }

}

This is complete code, which provides login, status update, image update to the point.

For detail see following link. http://javatechig.com/android/using-facebook-sdk-in-android-example

Share:
41,724

Related videos on Youtube

user782104
Author by

user782104

php

Updated on July 05, 2022

Comments

  • user782104
    user782104 almost 2 years

    I am working on custom facebook login button, I found that there is little source (especially working code example) about the latest facebook android sdk. I spent all day but still the code is not working. I wonder if there is any project example or your project code of:

    1. facebook login:
    2. share session to other activity/fragment (so I can check the login / logout status in everywhere of the app)
    3. post to wall
    4. logout

    Here are my code, but it actually return non-login status even I am logined

    Login:

    public class Login {
        private final static String TAG = "FaceBookLogin";
        public Context ctx;
        public Session fb_session;
    
        public Login(Context _ctx) {
            ctx = _ctx;
            Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
            fb_session = Session.getActiveSession();
    
            if(fb_session == null)                   
                fb_session = Session.openActiveSessionFromCache(ctx);
        }
    
        public void checkLogin() {
            printHashKey();
            if (fb_session != null && fb_session.isOpened()) {
                Log.i(TAG, "Facebook Login State");
            } else {
                if (fb_session == null)
                    fb_session = new Session(ctx);
    
                Session.setActiveSession(fb_session);
                ConnectToFacebook();
                Log.i(TAG, "Facebook Not login State");
            }
        }
    
        public void printHashKey() {
    
            try {
                PackageInfo info = ctx.getPackageManager().getPackageInfo("com.project.hkseven",
                        PackageManager.GET_SIGNATURES);
                for (Signature signature : info.signatures) {
                    MessageDigest md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
                    Log.d(TAG,
                            Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
            } catch (NameNotFoundException e) {
                  Log.d(TAG,""+e);
            } catch (NoSuchAlgorithmException e) {
                  Log.d(TAG,""+e);
            }
    
        }
    
        private void ConnectToFacebook() {
            Session session = Session.getActiveSession();
    
            if(session == null)                   
                session = Session.openActiveSessionFromCache(ctx);
    
            if (!session.isOpened() && !session.isClosed()) {
                Log.i(TAG, "ConnectToFacebook if");
                OpenRequest newSession = new Session.OpenRequest((Activity) ctx);
                newSession.setCallback(callback);
                session.openForRead(newSession);
                try {
                    Session.OpenRequest request = new Session.OpenRequest((Activity) ctx);
                    request.setPermissions(Arrays.asList("email","publish_stream","publish_actions"));
                } catch (Exception e) {
                    Log.d(TAG,""+e);
                    e.printStackTrace();
                }
            } else {
                Log.i(TAG, "ConnectToFacebook else");
                Session.openActiveSession((Activity) ctx, true, callback);
            }
        }
    
        private Session.StatusCallback callback = new Session.StatusCallback() {
            public void call(final Session session, final SessionState state,
                    final Exception exception) {
                Log.d(TAG,"callback" + state);
                onSessionStateChange(session, state, exception);
            }
        };
    
        private void onSessionStateChange(final Session session,
                SessionState state, Exception exception) {
            Log.i(TAG, "state change");
            if (session != null && session.isOpened()) {
                Log.i(TAG, "Change to Facebook Login");
            }
        }
    }
    

    Any kind of help is appreciate , thanks for kindly help

  • user782104
    user782104 about 10 years
    Thanks for your help , actually I had go through it before. I looked into SessionLoginSample but that is not so easy to understand and it provide some non-essential code in it. I think I am going to read the hellofacebook one.
  • user782104
    user782104 about 10 years
    I am looking for some tutorial like this: polamreddyn.blogspot.in/2013/12/… . Unfortunatelly this example is not working
  • Sagar Shah
    Sagar Shah about 10 years
    I prefer you to first go for Session Login sample then Hellofaebook.
  • Sagar Shah
    Sagar Shah about 10 years
    This is also good tutorial but It is from old sdk: Check it out if you like to: androidhive.info/2012/03/android-facebook-connect-tutorial
  • user782104
    user782104 about 10 years
    Thanks for your help. I am customzing the Session Login sample and hope it work with the hellosimple for publishing message
  • Paresh Mayani
    Paresh Mayani about 10 years
    It's link only answer, you must include essential part from the original source because link might be broken or may no longer exist in future.
  • Faisal Basra
    Faisal Basra about 10 years
    @PareshMayani Please, see my above updated post.
  • Pir Fahim Shah
    Pir Fahim Shah almost 10 years
    @FaisalBasra bhaie thumbs up for you...!
  • mehmetakifalp
    mehmetakifalp almost 10 years
    Actually I dont find anyway for importing facebook jars. Do you know about using jar file with gradle? do you have any code for gradle, auto-import? I m using android studio and I need jar file or gradle code.
  • Eenvincible
    Eenvincible almost 10 years
    What editor are you using?
  • Bhoomika Brahmbhatt
    Bhoomika Brahmbhatt almost 10 years
    Its giving null value for Email in case of native app is installed in device
  • Nitesh Verma
    Nitesh Verma over 9 years
    could you post the code for the manifest file please?
  • Apfelsaft
    Apfelsaft over 9 years
    @Faisal Bastra: You forgot to call postStatusMessage() inside the updateStatusBtn click listener.
  • Victor Laerte
    Victor Laerte over 9 years
    Nice answer! Helped a lot
  • madhu527
    madhu527 about 9 years
    u saved my day thanx a lot
  • pipacs
    pipacs almost 9 years
    Not working anymore: there is no com.facebook.widget.LoginButton.UserInfoChangedCallback in the latest SDK.
  • iOSAndroidWindowsMobileAppsDev
    iOSAndroidWindowsMobileAppsDev almost 8 years
    @pipacs I see you did not accept the answer and added that the example in the link provided stopped working. How did you resolve the matter?
  • iOSAndroidWindowsMobileAppsDev
    iOSAndroidWindowsMobileAppsDev almost 8 years
    @Faisal Basra does the link provided work, is the code up-to-date?
  • Huy Tower
    Huy Tower over 7 years
    Which Android Facebook SDK version you use in this answer?