开发者

Facebook login through android

开发者 https://www.devze.com 2023-04-08 02:34 出处:网络
I write an Android application that integrates facebook, but failing in the login to facebook step. What I\'m doing basically is to perform authorization and then ask if the session is valid. The answ

I write an Android application that integrates facebook, but failing in the login to facebook step. What I'm doing basically is to perform authorization and then ask if the session is valid. The answer is always negative. If I'm trying a simple request like:

 String response = facebookClient.request("me"); 

I am getting this response:

{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException"}}

Maybe I have the wrong hash key (through I read pretty good thr开发者_如何学JAVAeads how to get it right). I'd like to know if this is a way to insure key is matching.

I based my code on this - Android/Java -- Post simple text to Facebook wall?, and add some minor changes. This is the code:

public class FacebookActivity extends Activity implements DialogListener
{

    private Facebook facebookClient;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);//my layout xml  

    }



    public void login(View view)
    {
            facebookClient = new Facebook("my APP ID");
            facebookClient.authorize(this, this);
            if (facebookClient.isSessionValid() == true)
                Log.d("Valid:", "yes");
            else
                Log.d("Valid:", "no");
    }
}


Note that authorize method is asynchronous.

You should implement an onComplete method of DialogListener and make all the work you need (such as graph API me request) there.


Use following code in your app:

public class FacebookLogin {
    private AsyncFacebookRunner mAsyncRunner;
    private Facebook facebook;
    private Context mContext;
    private String mFName;

     public static final String[] PERMISSIONS = new String[] {"email", "publish_checkins", "publish_stream","offline_access"};

    public FacebookLogin(Context mContext) {
        this.mContext=mContext;
        facebook=new Facebook(YOUR_APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
    }

    public void Login() {
        facebook.authorize((Activity) mContext,PERMISSIONS,Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
    }

    public void Logout() throws MalformedURLException, IOException {
        facebook.logout(mContext);
    }
    public boolean isValidUser() {
        return facebook.isSessionValid();
    }

    class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            //Save the access token and access expire for future use in shared preferece
               String profile=facebook.request("me")
               String uid = profile.getString("id");
                mFName= profile.optString("first_name");
               new Session(facebook, uid, mFName).save(mContext);
        }

        public void onFacebookError(FacebookError error) {
            displayMessage("Opps..! Check for Internet Connection, Authentication with Facebook failed.");  
        }

        public void onError(DialogError error) {
            displayMessage("Opps..! Check for Internet Connection, Authentication with Facebook failed.");  
        }

        public void onCancel() {
            displayMessage("Authentication with Facebook failed due to Login cancel."); 
        }
    }
}

On Login complete save the facebook access token and access expire in your shared preference and while using again facebook object later set that access token and access expire to facebook object , it will not give the error which occurs in your code.

you can use following class :

public class Session {

    private static Session singleton;
    private static Facebook fbLoggingIn;

    // The Facebook object
    private Facebook fb;

    // The user id of the logged in user
    private String uid;

    // The user name of the logged in user
    private String name;

    /**
     * Constructor
     * 
     * @param fb
     * @param uid
     * @param name
     */
    public Session(Facebook fb, String uid, String name) {
        this.fb = fb;
        this.uid = uid;
        this.name = name;
    }

    /**
     * Returns the Facebook object
     */
    public Facebook getFb() {
        return fb;
    }

    /**
     * Returns the session user's id
     */
    public String getUid() {
        return uid;
    }

    /**
     * Returns the session user's name 
     */
    public String getName() {
        return name;
    }

    /**
     * Stores the session data on disk.
     * 
     * @param context
     * @return
     */
    public boolean save(Context context) {

            Editor editor =
           context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE).edit();
            editor.putString(ConstantsFacebook.TOKEN, fb.getAccessToken());
            editor.putLong(ConstantsFacebook.EXPIRES, fb.getAccessExpires());
            editor.putString(ConstantsFacebook.UID, uid);
            editor.putString(ConstantsFacebook.NAME, name);
            editor.putString(ConstantsFacebook.APP_ID, fb.getAppId());
            editor.putBoolean(ConstantsFacebook.LOGIN_FLAG,true);
        if (editor.commit()) {
            singleton = this;
            return true;
            }
        return false;
    }

    /**
     * Loads the session data from disk.
     * 
     * @param context
     * @return
     */
    public static Session restore(Context context) {
        if (singleton != null) {
            if (singleton.getFb().isSessionValid()) {
                return singleton;
            } else {
                return null;
            }
        }

        SharedPreferences prefs =
            context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);

            String appId = prefs.getString(ConstantsFacebook.APP_ID, null);

        if (appId == null) {
            return null;
        }

        Facebook fb = new Facebook(appId);
        fb.setAccessToken(prefs.getString(ConstantsFacebook.TOKEN, null));
        fb.setAccessExpires(prefs.getLong(ConstantsFacebook.EXPIRES, 0));
        String uid = prefs.getString(ConstantsFacebook.UID, null);
        String name = prefs.getString(ConstantsFacebook.NAME, null);

        if (!fb.isSessionValid() || uid == null || name == null) {
            return null;
        }

        Session session = new Session(fb, uid, name);
        singleton = session;
        return session;
    }

    /**
     * Clears the saved session data.
     * 
     * @param context
     */
    public static void clearSavedSession(Context context) {
        Editor editor = 
            context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE).edit();
        editor.clear();
        editor.commit();
        singleton = null;
    }

    /**
     * Freezes a Facebook object while it's waiting for an auth callback.
     */
    public static void waitForAuthCallback(Facebook fb) {
        fbLoggingIn = fb;
    }

    /**
     * Returns a Facebook object that's been waiting for an auth callback.
     */
    public static Facebook wakeupForAuthCallback() {
        Facebook fb = fbLoggingIn;
        fbLoggingIn = null;
        return fb;
    }

    public static String getUserFristName(Context context) {
         SharedPreferences prefs =
                    context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
         String frist_name = prefs.getString(ConstantsFacebook.NAME, null);
         return frist_name;

    }

    public static boolean checkValidSession(Context context) {
        SharedPreferences prefs =
                context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
        Boolean login=prefs.getBoolean(ConstantsFacebook.LOGIN_FLAG,false);
        return login;
    }


}
0

精彩评论

暂无评论...
验证码 换一张
取 消