0

我正在尝试使用 Facebook sdk 登录 Facebook。但它没有登录。它打开了对话框,但在获得凭据后它不起作用。如果我安装 Facebook 应用程序,它会打开 Facebook 应用程序但登录未完成,我无法获取令牌和用户 ID。我也不能把消息贴到墙上。但是它显示了“消息成功显示”的吐司,但没有发布在Facebook墙上。代码:

public boolean isSession() {
    access_token = sp.getString(TOKEN, "x");
    expires = sp.getLong(EXPIRES, -1);
    Log.d("TAG", access_token);

    if (access_token != null && expires != -1) {
        facebook.setAccessToken(access_token);
        facebook.setAccessExpires(expires);
    }
    return facebook.isSessionValid();
}

private class LoginDialogListener implements DialogListener {
    @Override
    public void onComplete(Bundle values) {
        Log.d("TAG", "LoginONComplete");
        token =facebook.getAccessToken();
        token_expires = facebook.getAccessExpires();
        Log.d("TAG", "AccessToken: " + token);
        Log.d("TAG", "AccessExpires: " + token_expires);

        savePrefs3(EXPIRES,token_expires);
        savePrefs(TOKEN,token);
        mAsyncRunner.request("me", new IDRequestListener());
    }

    @Override
    public void onFacebookError(FacebookError e) {
        Log.d("TAG", "FacebookError: " + e.getMessage());
    }

    @Override
    public void onError(DialogError e) {
        Log.d("TAG", "Error: " + e.getMessage());
    }

    @Override
    public void onCancel() {
        Log.d("TAG", "OnCancel");
    }
}

private class IDRequestListener implements RequestListener {
    @Override
    public void onComplete(String response, Object state) {
        try {
            Log.d("TAG", "IDRequestONComplete");
            Log.d("TAG", "Response: " + response.toString());
            JSONObject json = Util.parseJson(response);

            Uid = json.getString("id");
            savePrefs("UID", Uid);
            final String name = json.getString("name");
        } catch (JSONException e) {
            Log.d("TAG", "JSONException: " + e.getMessage());
        } catch (FacebookError e) {
            Log.d("TAG", "FacebookError: " + e.getMessage());
        }
    }

    @Override
    public void onIOException(IOException e, Object state) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e, Object state) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onMalformedURLException(MalformedURLException e, Object state) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
        // TODO Auto-generated method stub
    } 
}

public void postToWall(String message){
    Bundle parameters = new Bundle();
    parameters.putString("message", message);
    parameters.putString("description", "topic share");
    try {
        facebook.request("me");
        String response = facebook.request("me/feed", parameters, "POST");
        Log.d("Tests", "got response: " + response);
        if (response == null || response.equals("") ||
            response.equals("false")) {
            showToast("Blank response.");
        } else {
        showToast("Message posted to your facebook wall!");
        }
        finish();
    } catch (Exception e) {
        howToast("Failed to post to wall!");
        e.printStackTrace();
        finish();
    } 
}

private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}

请告诉我哪里出错了。显示吐司应用程序后关闭。在加载 fb 对话框时,如果我触摸屏幕,它会重新加载或切换回应用程序窗口。请立即回复

4

2 回答 2

4

Facebook 对象已折旧。您可以在活动的oncreate()方法中使用以下代码。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    requestWindowFeature(Window.FEATURE_NO_TITLE);

//  setContentView(R.layout.facebook_dialog);
    Session.openActiveSession(this, true, new Session.StatusCallback() {

        // callback when session changes state
        @Override
        public void call(Session session, SessionState state, Exception      exception) {
            if (session.isOpened()) {
                // make request to the /me API
                Request.executeMeRequestAsync(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(LoginFacebook.this.getApplicationContext(), 
                                    "Facebook Error",

Toast.LENGTH_LONG).show();

 finish();
                        }
                        else
                        {

         Toast.makeText(LoginFacebook.this.getApplicationContext(), 
                                    user.getName()+" Logged in Successfully.",
                                    T    
   Toast.LENGTH_LONG).show();
                            finish();
                        }
                        //login_fb.setEnabled(true);
                        //progress.setVisibility(View.INVISIBLE);
                    }

                });


            }
        }
    });


}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
  finish();
}

并在应用程序标记下的Manifest.xml文件中使用以下代码。

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

    <activity
        android:name="com.facebook.LoginActivity"
        android:label="@string/app_name" >
    </activity>

登录后发布到墙上,您必须调用此方法...

       private void publishStory(String user) {
    try {
        Session session = Session.getActiveSession();

        if (session != null){

            // Check for publish permissions    
            List<String> permissions = session.getPermissions();
            if (!isSubsetOf(PERMISSIONS, permissions)) {
                pendingPublishReauthorization = true;
                Session.NewPermissionsRequest newPermissionsRequest = new Session
                        .NewPermissionsRequest(this, PERMISSIONS);
                session.requestNewPublishPermissions(newPermissionsRequest);
                return;
            }

            Bundle postParams = new Bundle();
            postParams.putString("message", messageToPost);

            Request.Callback callback= new Request.Callback() {
                public void onCompleted(Response response) {
                    JSONObject graphResponse = response
                            .getGraphObject()
                            .getInnerJSONObject();
                    String postId = null;
                    try {
                        postId = graphResponse.getString("id");
                    } catch (Exception e) {
                        Log.i("Test",
                                "JSON error "+ e.getMessage());
                    }
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        Toast.makeText(ShareOnFacebook.this
                                .getApplicationContext(),
                                error.getErrorMessage(),
                                Toast.LENGTH_SHORT).show();
                    } else {

                        progress.setVisibility(View.INVISIBLE);
                        toastmessage="Posted Successfully";
                        Toast.makeText(ShareOnFacebook.this
                                .getApplicationContext(),
                                toastmessage,
                                Toast.LENGTH_SHORT).show();

                    }
                }
            };

            Request request = new Request(session, user+"/feed", postParams, 
                    HttpMethod.POST, callback);

            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Toast.makeText(ShareOnFacebook.this
                .getApplicationContext(),
                "Facebook Error",
                Toast.LENGTH_SHORT).show();
    }

}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
    for (String string : subset) {
        if (!superset.contains(string)) {
            return false;
        }
    }
    return true;
}

并将变量声明为..

private static final List<String> PERMISSIONS =    Arrays.asList("publish_actions","manage_pages","publish_stream");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
于 2013-05-24T11:48:25.240 回答
0

不完全是您问题的答案,但如果您开始开发您的应用程序:Facebook在 3.x API 中不推荐使用对象。在新 API 中,您应该使用Session对象,以及UiLifecycleHelper

于 2013-05-24T07:49:37.517 回答