登录失败后发布到Facebook的Android

时间:2013-07-16 17:34:34

标签: android facebook-android-sdk

在我的postToFacebook()方法中。我检查了用户是否已连接,如果我在墙上发布了一个链接。当用户未登录时,会弹出facebook sdk登录进度,并使用我的凭据成功登录。我的问题是登录后我需要直接postonWall,但postOnWall没有发布到Facebook。如果我已登录并发布,则会发布。请帮忙。这是我的完整postToFacebook代码。

public void postToFacebook(){


        mAsyncRunner = new AsyncFacebookRunner(facebook);

        loginToFacebook();
    }



    /**
     * Function to login into facebook
     * */
    public void loginToFacebook() {

        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);

        if (access_token != null) {
            facebook.setAccessToken(access_token);

            /*btnFbLogin.setVisibility(View.INVISIBLE);

            // Making get profile button visible
            btnFbGetProfile.setVisibility(View.VISIBLE);

            // Making post to wall visible
            btnPostToWall.setVisibility(View.VISIBLE);

            // Making show access tokens button visible
            btnShowAccessTokens.setVisibility(View.VISIBLE);*/

            new loadingTask().execute();

            System.out.println("one");
            Log.d("FB Sessions", "" + facebook.isSessionValid());
        }

        if (expires != 0) {
            facebook.setAccessExpires(expires);
        }

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

                            // Making Login button invisible
                            /*btnFbLogin.setVisibility(View.INVISIBLE);

                            // Making logout Button visible
                            btnFbGetProfile.setVisibility(View.VISIBLE);

                            // Making post to wall visible
                            btnPostToWall.setVisibility(View.VISIBLE);

                            // Making show access tokens button visible
                            btnShowAccessTokens.setVisibility(View.VISIBLE);*/

                            new loadingTask().execute();



                            System.out.println("two");
                        }

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

                        }

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

                        }

                    });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
    }



    /**
     * Function to show Access Tokens
     * */
    public void showAccessTokens() {
        String access_token = facebook.getAccessToken();

        Toast.makeText(getApplicationContext(),
                "Access Token: " + access_token, Toast.LENGTH_LONG).show();
    }


    /**
     * Function to Logout user from Facebook
     * */
    public void logoutFromFacebook() {
        mAsyncRunner.logout(this, new RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("Logout from Facebook", response);
                if (Boolean.parseBoolean(response) == true) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // make Login button visible
                            /*btnFbLogin.setVisibility(View.VISIBLE);

                            // making all remaining buttons invisible
                            btnFbGetProfile.setVisibility(View.INVISIBLE);
                            btnPostToWall.setVisibility(View.INVISIBLE);
                            btnShowAccessTokens.setVisibility(View.INVISIBLE);*/
                        }

                    });

                }
            }

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

    @SuppressWarnings("deprecation")
    public void postOWall(String msg) {

         Bundle params = new Bundle();
         params.putString("link", "http://google.com");

         mAsyncRunner.request("me/feed", params, "POST", new RequestListener() {

            @Override
            public void onComplete(String response, Object state) {
                // TODO Auto-generated method stub
                Log.i("onComplete", "complete");
            }
            @Override
            public void onIOException(IOException e, Object state) {

                // TODO Auto-generated method stub
                e.printStackTrace();

                Log.i("onComplete", "onIOException");

            }
            @Override
            public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
                // TODO Auto-generated method stub
                e.printStackTrace();
                Log.i("onComplete", "onFileNotFoundException");
            }
            @Override
            public void onMalformedURLException(MalformedURLException e,
                    Object state) {
                // TODO Auto-generated method stub
                e.printStackTrace();
                Log.i("onComplete", "onMalformedURLException");

            }
            @Override
            public void onFacebookError(FacebookError e, Object state) {
                // TODO Auto-generated method stub
                e.printStackTrace();
                Log.i("onComplete", "onFacebookError");
            }

//        try {
//              // String response = facebook.request("me");
//               Bundle parameters = new Bundle();
//               //parameters.putString("caption", "Test Caption");   
//               parameters.putString("link", "http://www.google.com");
//              // parameters.putString("caption", "Test Caption: http://google.com/");
//              // parameters.putString("method", "stream.publish");
////               response = facebook.request("me/feed", parameters, 
////                       "POST");
//               //Utility.mAsyncRunner.request("me", params, new UserRequestListener());
//              // Util.mAsyncRunner.request("me", parameters, new UserRequestListener());
//               mAsyncRunner.request("me/feed", parameters, "POST", new UserRequestListener(),null);
////               Log.d("Tests", "got response: " + response);
////               if (response == null || response.equals("") || 
////                       response.equals("false")) {
////                  Log.v("Error", "Blank response");
////               }
//        } catch(Exception e) {
//            e.printStackTrace();
//        }

    }, params);

}

    public void postOnWall(String link) {
        try {
               String response = facebook.request("me");
               Bundle parameters = new Bundle();
               //parameters.putString("caption", "Test Caption");  
               System.out.println("response link: "+link);
               parameters.putString("link", link);
              // parameters.putString("caption", "Test Caption: http://google.com/");
              // parameters.putString("method", "stream.publish");
               response = facebook.request("me/feed", parameters, 
                       "POST");

                FacebookSuccessMessage.title="";
                FacebookSuccessMessage.mesg="Posté sur Facebook";
                FacebookSuccessMessage.button_text="OK";

                Log.d("Tests", "got response: " + response);

                if (response!=null){
                    Intent i = new Intent (getApplicationContext(), FacebookSuccessMessage.class);
                    startActivity(i);
                }

               if (response == null || response.equals("") || 
                       response.equals("false")) {
                  Log.v("Error", "Blank response");
               }
        } catch(Exception e) {
            e.printStackTrace();
        }
   }


     class loadingTask extends AsyncTask<Void, Void,Void> {

          @Override
        protected void onPreExecute() {
        // TODO Auto-generated method stub

          super.onPreExecute();

        }

        @Override
        protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub


             super.onPostExecute(result);
        }

        @Override
        protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
            System.out.println("response c : "+ constants);
             postOnWall(constants);

            return null;
        }


     }

1 个答案:

答案 0 :(得分:1)

我已经测试了此代码,可以使用Facebook SDK 3.0进行发布,而这正在发挥作用。

在您当前的项目中引用Facebook SDK 3.0 Library项目。 在String.xml文件中设置AppId:

<string name="app_id">123456789012345</string>

之后在清单文件中添加MetaTag:

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

对于记录和退出,您只需使用Facebook登录按钮小部件“com.facebook.widget.LoginButton”

此小部件自动管理会话,因此您不必担心这一点 只需将此按钮放在Layout.xml文件中的正确位置即可 像任何其他按钮一样初始化此按钮:

LoginButton authButton = (LoginButton) findViewById(R.id.YOUR_ID);

初始化后,在LoginButton上设置权限

authButton.setPublishPermissions(Arrays.asList("publish_stream","read_stream"));

并实现Login按钮小部件的setSessionStatusCallback方法:

authButton.setSessionStatusCallback(new Session.StatusCallback() 
{
 public void call(Session session, SessionState state,Exception exception) 
{
// TODO Auto-generated method stub
if (session.isOpened()) 
    {
    Log.i(TAG, "Access Token" + session.getAccessToken());
    Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {

    public void onCompleted(GraphUser user,Response response) 
        {
        // TODO Auto-generated method stub
        if (user != null) 
            {
            Log.i(TAG, "User ID " + user.getId());
            Log.i(TAG,"Email "+ user.asMap().get("email"));
            }
        }});
    } 
    else 
    {
    //This else condition will be executed when logout will be clicked.
    }
}
});

以下是在Facebook上发布的方法。

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

if (session != null) 
    {
    Bundle postParams = new Bundle();
    postParams.putString("message", status);
    Request.Callback callback = new Request.Callback() 
        {
        public void onMalformedURLException(MalformedURLException e)
              {

              } 

        public void onIOException(IOException e) 
              {

              } 
        public void onFileNotFoundException(FileNotFoundExceptione) 
              {

              } 
        public void onFacebookError(FacebookError e) 
              {

              }


    public void onCompleted(Response response) 
    {
        JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
        String postId = null;
        try 
        {
            postId = graphResponse.getString("id");
        } 
        catch (JSONException e) 
        {
            Log.i("JSON", "JSON error " + e.getMessage());
        }
        FacebookRequestError error = response.getError();
        Log.e("post response", response.toString());
        if (error != null) 
        {
        } 
        else 
        {
        }
    }
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}