问题
In my postToFacebook() method. I checked if the user is connected if it is i post a link on my wall. When the user is not signed in, The facebook sdk login progress pop up and i login successfully using my credentials. My problem is after login i need to postonWall directly but the postOnWall is not posting to facebook. If i am already login and i post, then it is posted. Any help please. Here is my full postToFacebook code.
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:
I have tested this code for posting with Facebook SDK 3.0 and this is working.
Reference the Facebook SDK 3.0 Library project in your current project. Set the AppId in your String.xml file:
<string name="app_id">123456789012345</string>
After that add a MetaTag in your manifest file:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id" />
For Logging and and Logging out, you can simply use Facebook Login Button widget "com.facebook.widget.LoginButton".
This widget manages the Sessions automatically, so you do-not have to worry about that.
Just place this button in the right place in your Layout.xml file.
Initialize this button like any other buttons:
LoginButton authButton = (LoginButton) findViewById(R.id.YOUR_ID);
After initializing, set permissions on the LoginButton
authButton.setPublishPermissions(Arrays.asList("publish_stream","read_stream"));
and implement setSessionStatusCallback method of the Login button widget:
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.
}
}
});
Below is the method for posting on 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();
}
}
来源:https://stackoverflow.com/questions/17683338/post-to-facebook-after-login-fails-android