com.facebook.FacebookException:尝试使用未打开的会话 [英] com.facebook.FacebookException: Attempted to use a Session that was not open

查看:152
本文介绍了com.facebook.FacebookException:尝试使用未打开的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整合了Facebook分享,最近几天工作正常,但是今天只有2个小时才提出这个问题我正在面对这个问题。

I integrated facebook sharing, It was working fine from last few days, but today just 2 hours before asking this question I am facing this issue.

我正在使用此代码登录:

I am using this code for Login :

  Session.openActiveSession(this, true, new Session.StatusCallback() {

// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
  if (state.isOpened()) {

    // make request to the /me API
    Request.newMeRequest(session, new Request.GraphUserCallback() {

      // callback after Graph API response with user object
      @Override
      public void onCompleted(GraphUser user, Response response) {
        if (user != null) {

          Toast.makeText(ImagePagerActivity.this, user.getName()+" Logged In...", Toast.LENGTH_LONG).show();
        }
      }
    }).executeAsync();
  }
}
});
publishFeedDialog();

问题是if()条件总是错误的,我也用 session.isOpened()这也是返回false,我很困惑为什么会发生这种情况。

The problem is in if() condition which is always false, also I used session.isOpened() which is also returning false, I am confused why this happened.

我已经宣布INTERNET,ACCESSNETWORKSTATE,清单也

I have declared INTERNET,ACCESSNETWORKSTATE, permission in manifest also

 <application>
 ..........
 ..........
 <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
 </application>

请帮助...

EDIT

这是我实现的代码,你可以看到 onCreateOptionsMenu onOptionsItemSelected onActivityResult publishFeedDialog

This is the code of what I have implemented, you can see onCreateOptionsMenu , onOptionsItemSelected, onActivityResult, publishFeedDialog

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_bar_share_menu, menu);
        MenuItem item = menu.findItem(R.id.menu_item_share1);


        return true;
    }
@Override

public boolean      onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_share1: // facebook item selected
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
//start Facebook Login


Session.openActiveSession(this, true, new Session.StatusCallback() {

// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
  if (state.isOpened()) {

    // make request to the /me API
    Request.newMeRequest(session, new Request.GraphUserCallback() {

      // callback after Graph API response with user object
      @Override
      public void onCompleted(GraphUser user, Response response) {
        if (user != null) {

          Toast.makeText(ImagePagerActivity.this, user.getName()+" Logged In...", Toast.LENGTH_LONG).show();
        }
      }
    }).executeAsync();
  }
}
});
publishFeedDialog();

}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.e("Activity", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.i("Activity", "Success!");
        }
    });

}
@Override
protected void onResume() {
    super.onResume();
    uiHelper.onResume();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(STATE_POSITION, pager.getCurrentItem());
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
}

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

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

private void publishFeedDialog() {

    Log.v("pos",""+pos);
    Bundle params = new Bundle();
    params.putString("name", ItemListApplication.names.get(pos).getItem());
    params.putString("caption", "Irrational beliefs");
    params.putString("description",ItemListApplication.names.get(pos).getDesc() );
    params.putString("link", "https://www.facebook.com/vivek.warde.3?ref=tn_tnmn");

    if(pos==0) params.putString("picture","http://i.imgur.com/lOIUcW2.jpg");
    else params.putString("picture",imageUrls[pos]);
    WebDialog feedDialog = (
        new WebDialog.FeedDialogBuilder(this,
            Session.getActiveSession(),
            params))
        .setOnCompleteListener(new OnCompleteListener() {

            @Override
            public void onComplete(Bundle values,
                FacebookException error) {
                if (error == null) {
                    // When the story is posted, echo the success
                    // and the post Id.
                    final String postId = values.getString("post_id");
                    if (postId != null) {
                        Toast.makeText(ImagePagerActivity.this,
                            "Posted story, id: "+postId,
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // User clicked the Cancel button
                        Toast.makeText(ImagePagerActivity.this, 
                            "Publish cancelled", 
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (error instanceof FacebookOperationCanceledException) {
                    // User clicked the "x" button
                    Toast.makeText(ImagePagerActivity.this, 
                        "Publish cancelled", 
                        Toast.LENGTH_SHORT).show();
                } else {
                    // Generic, ex: network error
                    Toast.makeText(ImagePagerActivity.this, 
                        "Error posting story", 
                        Toast.LENGTH_SHORT).show();
                }
            }

        })
        .build();
    feedDialog.show();
}


推荐答案

有这个问题。你应该检查一下:

It can be many reasons dealing with this problem. You should check some of this:

我正在使用此代码通过Facebook登录:

I'm using this code for login via facebook:

class MyFragment extends Fragment {
   //... some code

   SessionStatusCallback statusCallback = new SessionStatusCallback();

   public void login() {
       Session session = Session.getActiveSession();
       if (!session.isOpened() && !session.isClosed()) {
           session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
       } else {
           Session.openActiveSession(getActivity(), this, true, statusCallback);
       }
   }

   private class SessionStatusCallback implements Session.StatusCallback {
       @Override
       public void call(Session session, SessionState state, Exception exception) {
           if (exception != null) {
               handleException(exception);
           }
           if (state.isOpened()) {
               afterLogin();
           } else if (state.isClosed()) {
               afterLogout();
           }
        }
    }

}

如果会话未被打开,您应该打开它以进行阅读(或发布,如果你需要)。

If session wasn't opened you should open it for read (or for publish if you need).

在AndroidManifest文件中检查元数据标签,是否正确的应用程序ID?

Check meta-data tag in AndroidManifest file, is there correct application id?

经常发生的错误不在Android应用程序内,而是在Facebook应用程序设置中。在Facebook应用程序的设置页面应该是正确的包名称,您应该为应用程序添加密钥哈希(不同于每个版本类型,在大多数情况下是调试和释放)。

Often happens that error not inside android application but in facebook application settings. In facebook application's settings page should be correct package name, and you should add key hashes for you application (different for every release type, in most cases is debug and release).

要获取散列键,您可以运行脚本

To get hash key you can run script

keytool -exportcert -alias YOUR_ALIAS -keystore PATH_TO_KEYSTORE_FILE | openssl sha1 -binary | openssl base64

或者你可以在代码中找到它:

or you can get it inside code:

PackageInfo info;
try {
    info = getPackageManager().getPackageInfo("YOUR_APP_PACKAGE", PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        String keyhash = new String(Base64.encode(md.digest(), 0));
        //string something is what you should paste as key hash
        Log.e("hash key", keyhash);
    }
} catch (NameNotFoundException e1) {
    Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
    Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
    Log.e("exception", e.toString());
} 






在Facebook应用程序的设置页面内部状态&评论选项卡应该使应用程序公开。或者如果您仍然不希望将其公开,则应为可以使用Android应用程序的所有用户添加角色(在角色选项卡内)。


In facebook application's settings page inside Status & Review tab you should make app public. Or if you still don't want to make it public, you should add roles for all users that can use your android application (inside Roles tab).

另外,如果没有帮助,尝试调试方法

public void call(Session session,SessionState state,Exception exception)

通常有一些常见的消息,为什么授权不成功

Also, if it don't help, try to debug method
public void call(Session session, SessionState state, Exception exception)
There often normal messages why authorization wasn't successful

这篇关于com.facebook.FacebookException:尝试使用未打开的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆