com.facebook.FacebookException:尝试使用未打开的Session

时间:2014-07-09 14:45:12

标签: android facebook

我整合了facebook分享,从最近几天开始工作正常,但是今天在问这个问题之前的2个小时我正面临着这个问题。

我正在使用此代码进行登录:

  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,我很困惑为什么会发生这种情况。

我已经宣布了INTERNET,ACCESSNETWORKSTATE,清单中的权限

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

请帮忙......

修改

这是我已实施的代码,您可以看到onCreateOptionsMenuonOptionsItemSelectedonActivityResultpublishFeedDialog

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

2 个答案:

答案 0 :(得分:6)

处理这个问题可能有很多原因。你应该检查一下:

我使用此代码通过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();
           }
        }
    }

}

如果会话未打开,则应将其打开以供阅读(如果需要,可打开publish)。


检查AndroidManifest文件中的meta-data标记,是否有正确的应用程序ID?


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

facebook android settings

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

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

或者你可以在代码中获取它:

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

在状态&amp;中的Facebook应用程序设置页面中审核标签,您应该公开app。或者,如果您仍然不想将其公开,则应为可以使用Android应用程序的所有用户添加角色(在“角色”选项卡中)。


此外,如果它没有帮助,请尝试调试方法
public void call(Session session, SessionState state, Exception exception)
通常有正常的消息,为什么授权不成功

答案 1 :(得分:0)

 **generate keyhash from facebook api and then** 

 running this in to commandprompt/ terminal 

 keytool -exportcert -alias YOUR_ALIAS_NAME -keystore PATH_TO_KEYSTORE_FILE | openssl sha1 -binary | openssl base64
Android.Manifest文件中的

<meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/app_id" />
在demofacebookLogin(活动文件)

private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;


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

    facebook = new Facebook(APP_ID);

    mAsyncRunner = new AsyncFacebookRunner(facebook);

 }

 public void loginToFacebook() {
    mPrefs = getPreferences(MODE_PRIVATE);
    if (!facebook.isSessionValid()) {
        facebook.authorize(this,
                new String[] { "email", "publish_stream" },
                new DialogListener() {

                    @Override
                    public void onCancel() {
                        // Function to handle cancel event
                    }

                    @Override
                    public void onComplete(Bundle values) {
                        // Function to handle complete event
                        // Edit Preferences and update facebook acess_token
                        SharedPreferences.Editor editor = mPrefs.edit();
                        editor.putString("access_token",
                                facebook.getAccessToken());
                        editor.putLong("access_expires",
                                facebook.getAccessExpires());
                        editor.commit();
                        getProfileInformation();
                    }

                    @Override
                    public void onError(DialogError error) {
                        // Function to handle error

                    }

                    @Override
                    public void onFacebookError(FacebookError fberror) {
                        // Function to handle Facebook errors

                    }

                });
    }
}



    public void getProfileInformation() {
    mAsyncRunner.request("me", new RequestListener() {
        @Override
        public void onComplete(String response, Object state) {
            Log.d("Profile", response);
            String json = response;
            try {
                JSONObject profile = new JSONObject(json);
                // getting name of the user
                facebook_FB_Id = profile.getString("id");
                facebook_username = profile.getString("name");
                // getting email of the user
                facebook_email = profile.getString("email");
                facebook_firstname = profile.getString("first_name");
                facebook_lastname = profile.getString("last_name");
                facebook_FbLink = profile.getString("link");

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        Log.i("", facebook_FB_Id + " == "
                                + facebook_username + " =="
                                + facebook_FbLink);

                        Intent startRegistrationTypeActivity = new Intent(
                                getContext(),
                                RegistrationTypeActivity.class);
                        startRegistrationTypeActivity.putExtra(
                                "facebook_FB_Id", facebook_FB_Id);
                        startRegistrationTypeActivity.putExtra(
                                "facebook_username", facebook_username);
                        startRegistrationTypeActivity.putExtra(
                                "facebook_email", facebook_email);
                        startRegistrationTypeActivity.putExtra(
                                "facebook_firstname", facebook_firstname);
                        startRegistrationTypeActivity.putExtra(
                                "facebook_lastname", facebook_lastname);
                        startRegistrationTypeActivity.putExtra(
                                "facebook_FbLink", facebook_FbLink);
                        startActivity(startRegistrationTypeActivity);

                    }

                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onIOException(IOException e, Object state) {
        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e,
                Object state) {
        }

        @Override
        public void onMalformedURLException(MalformedURLException e,
                Object state) {
        }

        @Override
        public void onFacebookError(FacebookError e, Object state) {
        }
    });

}