简体   繁体   English

通过android登录Facebook

[英]Facebook login through android

I write an Android application that integrates facebook, but failing in the login to facebook step. 我编写了一个集成了Facebook的Android应用程序,但是登录到Facebook步骤失败。 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"}} {“ error”:{“ message”:“必须使用活动访问令牌来查询有关当前用户的信息。”,“ type”:“ OAuthException”}}

Maybe I have the wrong hash key (through I read pretty good threads 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? 我基于此代码-Android / Java-将简单文本发布到Facebook墙? , 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");
    }
}

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. 登录完成后,以您的共享首选项保存facebook访问令牌和访问权限,然后再次使用facebook对象时,将该访问令牌和访问权限设置为facebook对象,它将不会给出代码中发生的错误。

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;
    }


}

Note that authorize method is asynchronous. 请注意,authorize方法是异步的。

You should implement an onComplete method of DialogListener and make all the work you need (such as graph API me request) there. 您应该实现DialogListener的onComplete方法,并在那里进行所需的所有工作(例如我请求的图形API)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM