【问题标题】:How to create session using FB page access token如何使用 FB 页面访问令牌创建会话
【发布时间】:2014-10-18 10:00:48
【问题描述】:

我创建了一个long-lasting Facebook 访问令牌。我有一个来自 Facebook 的 TestApp 的应用 ID。问题是我似乎无法获得有效的会话!我做错了什么?

public class MainActivity extends Activity {
    Facebook fb;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fb = new Facebook(getString(R.string.APP_ID));
        fb.setAccessToken(getString(R.string.ACCESS_TOKEN));
        //Expiry is set to 0, since the token never expires
        fb.setAccessExpires(0);



        if (fb.isSessionValid()) {

            Toast.makeText(this, "Session is valid",
                    android.widget.Toast.LENGTH_LONG).show();
            Log.d("TAG2", getString(R.string.ACCESS_TOKEN));

        } else
            Toast.makeText(this,
                    "Session is Invalid"+ getString(R.string.ACCESS_TOKEN),
                    android.widget.Toast.LENGTH_LONG).show();
            Log.d("TAG3", getString(R.string.ACCESS_TOKEN));


    }

}

编辑的代码(我编辑了我的原始代码以反映给出的两个答案,但仍然没有帮助):

public class MainActivity extends Activity {
    Facebook fb;
    SharedPreferences prefs;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         SharedPreferences.Editor editor = prefs.edit();
         editor.putString("AKEY",getString(R.string.ACCESS_TOKEN));
         editor.commit();
         editor.apply();

        fb = new Facebook(getString(R.string.app_id));
        fb.setAccessToken(prefs.getString("AKEY", ""));
        //Expiry is set to 0, since the token never expires
        fb.setAccessExpires(0);

        if (fb.isSessionValid()) {

            Toast.makeText(this, "Session is validd",
                    android.widget.Toast.LENGTH_LONG).show();
            Log.d("TAG2", getString(R.string.ACCESS_TOKEN));

        } else {
            Toast.makeText(this, fb.toString(),
                    android.widget.Toast.LENGTH_LONG).show();
            Log.d("TAG3", fb.toString() + fb.getAccessExpires()
                    + "Access Token is: " + fb.getAccessToken() +prefs.getString("AKEY", "")
                    + "Last update is:" + fb.getLastAccessUpdate()
                    + "Session is:" + fb.getSession());
        }

    }

}

【问题讨论】:

  • 您使用旧 API 有什么原因吗?
  • @ItzikSamara 不,我认为这是使用 FB 的 API 获取会话的标准方式。
  • 如果您可以添加 Facebook 登录按钮,我会写下完整的答案。
  • @ItzikSamara 实际上我只需要从我管理的一个页面中获取状态。这就是为什么我创建了持久令牌以允许我监控页面。没有其他人会使用它。

标签: android facebook facebook-graph-api android-facebook


【解决方案1】:

使用 SharedPreference 将会话存储在 Android 中。

商店

SharedPreferences settings = context.getSharedPreferences("KEY_NAME",
                context.MODE_PRIVATE);

Editor editor = settings.edit();
editor.putInt("fbsession", session);
editor.commit();
editor.apply();

检索

 SharedPreferences settings = context.getSharedPreferences("KEY_NAME", context.MODE_PRIVATE);
 String fbSession = settings.getInt("fbsession", 1);

【讨论】:

  • 你能提供更多细节吗?你是什​​么意思存储会话?从代码中可以看出,根本没有返回有效的会话。
  • 我尝试了您提供的解决方案,但问题仍然存在。我已经发布了修改后的代码。
【解决方案2】:

您可以像这样编写代码以在首选项中添加价值

SharedPreferences prefs = context.getSharedPreferences("com.projectname.pkgname",
            Context.MODE_PRIVATE);
prefs.edit().putString("facebook_accesstoken", "your_token").commit();

像这样得到它

String facebook_accessstoken=prefs.getString("facebook_accesstoken", "");

【讨论】:

  • 懒人请自己动手
  • 我尝试了您提供的解决方案,但问题仍然存在。我已经发布了修改后的代码。
【解决方案3】:

我认为我能想到的对这种行为的唯一解释是我使用了已弃用的 API。根据新的 API 更改我的代码后,它现在可以工作了。如果在 Facebook 文档中明确说明这一点,将不胜感激。

public class MainActivity extends Activity {

    SharedPreferences prefs;

    Session session;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("AKEY",getString(R.string.ACCESS_TOKEN));
        editor.putLong("expire", 0);
        editor.commit();
        editor.apply();

        Session.StatusCallback callback = new Session.StatusCallback()
                       {
           @Override
           public void call(
               Session session,
               SessionState state,
               Exception exception)
           {
             // safety check
             if (isFinishing())
               return;

             // check session state

             if (state.equals(SessionState.CLOSED)
                 || state.equals(SessionState.CLOSED_LOGIN_FAILED))
             {
             //  clearFacebookInfoFromSharedPreferences();
                 Log.d("TAG A","clearFacebookInfoFromSharedPreferences()");

               // specific action for when the session is closed
               // because an open-session request failed
               if (state.equals(SessionState.CLOSED_LOGIN_FAILED))
               {

                   Log.d("TAG B","cancelProgressDialog()");

               }
             }
             else if (state.equals(SessionState.OPENED))
             {
             //  cancelProgressDialog();


               Toast.makeText(MainActivity.this, "Succeeded connecting to Facebook",    android.widget.Toast.LENGTH_LONG).show();


               //handler.onSuccess();
             }
           }
         };

if (Session.getActiveSession() == null
                  && prefs.contains("AKEY")
                  && prefs.contains("expire"))
              {
                // open a session from the access token info
                // saved in the app's shared preferences

                String accessTokenString = prefs.getString(
                    "AKEY",
                    "");

                Date accessTokenExpires = new Date(prefs.getLong(
                    "expire",
                    0));

                AccessToken accessToken = AccessToken.createFromExistingAccessToken(
                    accessTokenString,
                    accessTokenExpires,
                    null,
                    null,
                    null);

                session=Session.openActiveSessionWithAccessToken(this, accessToken, callback);

            if (session != null) {

            Toast.makeText(this, "Session is valid",
                    android.widget.Toast.LENGTH_LONG).show();
            Log.d("TAG2", ""+session.getExpirationDate()+session.getAccessToken());

        } else {
            Toast.makeText(this, "Session is invalid",
                    android.widget.Toast.LENGTH_LONG).show();

        }




            Bundle params = new Bundle();

            params.putString("fields", "likes.limit(1).summary(true)");
            Request request = new Request(session, "922169881132606", params, HttpMethod.GET, new Request.Callback() {

                @Override
                public void onCompleted(Response response) {
                    try {
                        Log.d("TAG5", "In Try block");
                        GraphObject go = response.getGraphObject();
                        Log.d("graph object is", go.toString());
                        JSONObject obj = go.getInnerJSONObject();
                        JSONObject arr = obj.getJSONObject("likes"); 
                        JSONObject res = arr.getJSONObject("summary");
                        Log.d("TAG23", "JSON Set");
                       int numberOfLikes = res.getInt("total_count");
                       Log.d("Number of likes is ", Integer.toString(numberOfLikes));
                       Toast.makeText(MainActivity.this, "Number of likes is",
                                android.widget.Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Log.d("An error was thrown","alpha"+e);
                        e.printStackTrace();
                    }
                }
            });
            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
           Log.d("TAG7", "task is executed");





    }

}

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2016-03-25
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多