com.facebook.FacebookException:试图使用一个会话没有打开 [英] com.facebook.FacebookException: Attempted to use a Session that was not open

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

问题描述

我Facebook的整合共享,这是从最近几天工作正常,但现在只需2小时问这个问题之前,我面对这个问题。

我用这code代表登录:

  Session.openActiveSession(这一点,真正的,新的Session.StatusCallback(){//回调时,会话状态变化
@覆盖
公共无效呼叫(会话的会话,SessionState会状态,异常除外){
  如果(state.isOpened()){    //使请求/我API
    Request.newMeRequest(会话,新Request.GraphUserCallback(){      //后用户对象图形API响应回调
      @覆盖
      公共无效onCompleted(GraphUser用户,响应响应){
        如果(用户!= NULL){          Toast.makeText(ImagePagerActivity.this,user.getName()+记录在......,Toast.LENGTH_LONG).show();
        }
      }
    })executeAsync()。
  }
}
});
publishFeedDialog();

问题是在这始终是假的,我也用IF()条件 session.isOpened()这也返回false,我很困惑,为什么发生这种情况。

我已经声明INTERNET,ACCESSNETWORKSTATE,在清单还允许

 <应用>
 ..........
 ..........
 <元数据机器人:名字=com.facebook.sdk.ApplicationId机器人:值=@字符串/ APP_ID/>
 < /用途>

请帮忙...

修改

这是什么,我已经实现了code,你可以看到 onCreateOptionsMenu onOptionsItemSelected 的onActivityResult publishFeedDialog

  @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        。getMenuInflater()膨胀(R.menu.action_bar_share_menu,菜单);
        菜单项项= menu.findItem(R.id.menu_item_share1);
        返回true;
    }
@覆盖公共布尔onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例R.id.menu_item_share1:// Facebook的选中项
Toast.makeText(这一点,菜单项选择1,Toast.LENGTH_SHORT).show();
//启动的Facebook登录
Session.openActiveSession(这一点,真正的,新的Session.StatusCallback(){//回调时,会话状态变化
@覆盖
公共无效呼叫(会话的会话,SessionState会状态,异常除外){
  如果(state.isOpened()){    //使请求/我API
    Request.newMeRequest(会话,新Request.GraphUserCallback(){      //后用户对象图形API响应回调
      @覆盖
      公共无效onCompleted(GraphUser用户,响应响应){
        如果(用户!= NULL){          Toast.makeText(ImagePagerActivity.this,user.getName()+记录在......,Toast.LENGTH_LONG).show();
        }
      }
    })executeAsync()。
  }
}
});
publishFeedDialog();}
返回true;
}
@覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
    super.onActivityResult(要求code,结果code,数据);    uiHelper.onActivityResult(要求code,结果code,数据,新FacebookDialog.Callback(){
        @覆盖
        公共无效onerror的(FacebookDialog.PendingCall pendingCall,异常错误,捆绑数据){
            Log.e(活动,的String.format(错误:%s,error.toString()));
        }        @覆盖
        公共无效的onComplete(FacebookDialog.PendingCall pendingCall,捆绑数据){
            Log.i(活动,成功!);
        }
    });}
@覆盖
保护无效onResume(){
    super.onResume();
    uiHelper.onResume();
}@覆盖
保护无效的onSaveInstanceState(捆绑outState){
    outState.putInt(STATE_POSITION,pager.getCurrentItem());
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
}@覆盖
公共无效的onPause(){
    super.onPause();
    uiHelper.onPause();
}@覆盖
公共无效的onDestroy(){
    super.onDestroy();
    uiHelper.onDestroy();
}私人无效publishFeedDialog(){    Log.v(POS,+正);
    捆绑PARAMS =新包();
    params.putString(名,ItemListApplication.names.get(POS).getItem());
    params.putString(标题,不合理的信念);
    params.putString(说明,ItemListApplication.names.get(POS).getDesc());
    params.putString(链接,https://www.facebook.com/vivek.warde.3?ref=tn_tnmn);    如果(POS == 0)params.putString(图片,http://i.imgur.com/lOIUcW2.jpg);
    其他params.putString(图片报,imageUrls [POS]);
    WebDialog feedDialog =(
        新WebDialog.FeedDialogBu​​ilder(这一点,
            Session.getActiveSession(),
            PARAMS))
        .setOnCompleteListener(新OnCompleteListener(){            @覆盖
            公共无效的onComplete(束值,
                FacebookException错误){
                如果(错误== NULL){
                    //当故事被张贴,呼应成功
                    //和帖子的ID。
                    最终字符串postid = values​​.getString(POST_ID);
                    如果(帖子ID!= NULL){
                        Toast.makeText(ImagePagerActivity.this,
                            张贴的故事,ID:+帖子ID,
                            Toast.LENGTH_SHORT).show();
                    }其他{
                        //用户点击了取消按钮
                        Toast.makeText(ImagePagerActivity.this,
                            发布取消
                            Toast.LENGTH_SHORT).show();
                    }
                }否则如果(错误的instanceof FacebookOperationCanceledException){
                    //用户点击X按钮
                    Toast.makeText(ImagePagerActivity.this,
                        发布取消
                        Toast.LENGTH_SHORT).show();
                }其他{
                    //通用,例如:网络错误
                    Toast.makeText(ImagePagerActivity.this,
                        错误张贴的故事
                        Toast.LENGTH_SHORT).show();
                }
            }        })
        。建立();
    feedDialog.show();
}


解决方案

它可以有很多原因,处理这一问题。您应该检查一些这样的:

我使用这个code为登录通过Facebook:

 类MyFragment扩展片段{
   // ...一些code   SessionStatusCallback statusCallback =新SessionStatusCallback();   公共无效登录(){
       会话的会话= Session.getActiveSession();
       如果(session.isOpened()及!&放大器;!session.isClosed()){
           session.openForRead(新Session.OpenRequest(本).setCallback(statusCallback));
       }其他{
           Session.openActiveSession(getActivity(),这个,真的,statusCallback);
       }
   }   私有类SessionStatusCallback实现Session.StatusCallback {
       @覆盖
       公共无效呼叫(会话的会话,SessionState会状态,异常除外){
           如果(例外!= NULL){
               handleException(例外);
           }
           如果(state.isOpened()){
               afterLogin();
           }否则如果(state.isClosed()){
               afterLogout();
           }
        }
    }}

如果会议不开了,你应该打开它进行读取(或<一个href=\"https://developers.facebook.com/docs/reference/android/current/class/Session/#openForPublish\">publish如果你需要)。


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


经常发生这样的错误不是Android应用程序内部,而是在Facebook应用程序设置。在Facebook应用程序的设置页面应该是正确的软件包名称,你应该添加关键哈希为你的应用程序(不同的每一个版本类型,在大多数情况下是调试和发布)。

要获得哈希键,您可以运行脚本

 密钥工具-exportcert -alias YOUR_ALIAS -keystore PATH_TO_KEYSTORE_FILE | OpenSSL的SHA1 -binary | OpenSSL的BASE64

或者你可以得到code里面:

  PackageInfo信息;
尝试{
    信息= getPackageManager()getPackageInfo(YOUR_APP_PACKAGE,PackageManager.GET_SIGNATURES)。
    对(签字签名:info.signatures){
        消息摘要MD;
        MD = MessageDigest.getInstance(SHA);
        md.update(signature.toByteArray());
        字符串keyhash =新的String(Base64.en code(md.digest(),0));
        //字符串的东西是你应该粘贴为重点的哈希什么
        Log.e(哈希键,keyhash);
    }
}赶上(E1的NameNotFoundException){
    Log.e(找不到名称,e1.toString());
}赶上(抛出:NoSuchAlgorithmException E){
    Log.e(没有这样的算法,e.toString());
}赶上(例外五){
    Log.e(异常,e.toString());
}


在Facebook应用程序的设置里面的状态和放大器的页面;评论选项卡,你应该让应用公开。或者,如果你还不想把它公开,您应该添加角色可以使用您的Andr​​oid应用程序(角色选项卡内)的所有用户。


另外,如果不帮忙,尝试调试方法结果
公共无效呼叫(会话的会话,SessionState会状态,异常除外)结果
经常有正常的消息,为什么授权不成功

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();

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.

I have declared INTERNET,ACCESSNETWORKSTATE, permission in manifest also

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

please help...

EDIT

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:

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).


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


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


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).


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天全站免登陆