1

我一直在使用此SDK http://www.easyfacebookandroidsdk.com/将Facebook集成到我的应用程序。 我只想从我的应用程序更新一个statur。它在Android API 10中使用这个类很好用。在API 15的手机上运行它给了我一个android.os.NetworkOnMainThreadException。这里我的代码:易Facebook的Android SDK - NetworkOnMainThreadException

package com.my.wod; 

import android.app.Activity; 
import android.content.Context; 
import com.main.xfit.R; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.Window; 
import android.widget.Toast; 


import com.facebook.android.*; 

import com.facebook.android.Facebook.DialogListener; 

public class PostFaceBookStatus extends Activity { 


private static final String APP_ID = "ID OF MY APP"; 
private static final String[] PERMISSIONS = {"publish_stream" }; 

private static final String TOKEN = "access_token"; 
    private static final String EXPIRES = "expires_in"; 
    private static final String KEY = "facebook-credentials"; 

private Facebook facebook; 
private String messageToPost; 

public boolean saveCredentials(Facebook facebook) { 
     Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); 
     editor.putString(TOKEN, facebook.getAccessToken()); 
     editor.putLong(EXPIRES, facebook.getAccessExpires()); 
     return editor.commit(); 
    } 

    public boolean restoreCredentials(Facebook facebook) { 
     SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE); 
     facebook.setAccessToken(sharedPreferences.getString(TOKEN, null)); 
     facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0)); 
     return facebook.isSessionValid(); 
    } 

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

    facebook = new Facebook(APP_ID); 
    restoreCredentials(facebook); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 

    setContentView(R.layout.facebook); 

    String facebookMessage = getIntent().getStringExtra("facebookMessage"); 
    Toast.makeText(getApplicationContext(), facebookMessage, Toast.LENGTH_LONG).show(); 
    if (facebookMessage == null){ 
     facebookMessage = "SUNDAY 120506 2012 CrossFit Games Regional: Individual Event 4 For time: 135 pound Back squat, 50 reps 40 Pull-ups 135 pound Shoulder-to-overhead, 30 reps 85 pound Front squat, 50 reps 40 Pull-ups 85 pound Shoulder-to-overhead, 30 reps 65 pound Overhead squat, 50 reps 40 Pull-ups 65 pound Shoulder-to-overhead, 30 reps"; 
    } 
    //messageToPost = facebookMessage; 
    messageToPost = "Post random shit" ; 
} 

public void doNotShare(View button){ 
    finish(); 
} 
public void share(View button){ 
    if (! facebook.isSessionValid()) { 
     loginAndPostToWall(); 
    } 
    else { 
     postToWall(messageToPost); 
    } 
} 

public void loginAndPostToWall(){ 
    facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener()); 
} 

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) { 
       showToast("Failed to post to wall!"); 
       e.printStackTrace(); 
       finish(); 
    } 
} 

class LoginDialogListener implements DialogListener { 
    public void onComplete(Bundle values) { 
     saveCredentials(facebook); 
     if (messageToPost != null){ 
     postToWall(messageToPost); 
    } 
    } 
    public void onFacebookError(FacebookError error) { 
     showToast("Authentication with Facebook failed!"); 
     finish(); 
    } 
    public void onError(DialogError error) { 
     showToast("Authentication with Facebook failed!"); 
     finish(); 
    } 
    public void onCancel() { 
     showToast("Authentication with Facebook cancelled!"); 
     finish(); 
    } 
} 

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

任何想法?

+0

您不能在UI线程上运行网络操作,如果您认为它是执行它的API代码,那么您将不得不将API调用包装到线程中。 – Blundell

回答

1

您无法在UI线程上运行网络操作,如果您认为它是执行此操作的API代码,那么您必须将该API调用包装到线程中。

貌似这条线是使用网络:

String response = facebook.request("me/feed", parameters, "POST"); 

你需要做一个工作线程长时间运行的任务。

你曾经得到过一个ANR(Activity Not Responsding),但是ICS有点聪明,在这种情况发生之前就把你踢开了。

获取阅读:

http://developer.android.com/guide/practices/responsiveness.html

http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask <这是一个可能的替代答案

+0

嗨,很好的答案完美工作。我很困惑,因为运行这个确切的类在Android API 10上工作正常。AsynkTask非常感谢您解决了这个问题! –

0

,使之成为API级10的工作,我只是使用和的AsyncTask和它的工作更高! 使用以下代码:

//使此全局声明 私人Facebook mFacebook;

private class FbLoginAsync extends AsyncTask<Void, Void, User> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     showDialog(ConstantsCtc.DIALOG_PROGRESS); 
    } 

    @Override 
    protected User doInBackground(Void... params) { 
     // facebooklogin(); 
     return getFacebookData(); 
    } 

    @Override 
    protected void onPostExecute(User u) { 
     super.onPostExecute(u); 
     // your facebook information is in User bean 'u'. 

    } 

} 

public User getFacebookData() { 
    User u = new User(); 
    try { 
     JSONObject jsonME = null; 
     JSONObject jsonfrnd = null; 
     try { 
      jsonME = Util.parseJson(mFacebook.request("me")); 
      // jsonfrnd = 
      // Util.parseJson(mFacebook 
      // .request("me/friends")); 
     } catch (FacebookError e) { 
      e.printStackTrace(); 
      u = null; 
     } 
     Log.w("fbjsonMe", " *\n " + jsonME); 
     // Log.e("fbjsonfrnds", " *\n " + jsonfrnd); 

     String mUserId = jsonME.getString("id"); 
     String mUserName = jsonME.getString("first_name"); 
     String mUseremail = jsonME.getString("email"); 
     String birthday = jsonME.getString("birthday"); 
     String gender = jsonME.getString("gender"); 
     String full_name = jsonME.getString("name"); 

     // Log.w("UserName", mUserName + " * " + mUseremail + " *\n " 
     // + jsonME); 

     // calculate age 
     String ag[] = birthday.split("/"); 
     int y = Integer.parseInt(ag[2]);// get birth year 
     final Calendar cal = Calendar.getInstance(); 
     int currentyear = cal.get(Calendar.YEAR); 
     int age = currentyear - y; 

     if (gender.equalsIgnoreCase("male")) 
      gender = "0"; 
     else 
      gender = "1"; 

     u.setUserId(mUserId); 
     u.setUserFullName(full_name); 
     u.setEmail(mUseremail); 
     u.setAge(age + ""); 
     u.setGender(gender); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     u = null; 
    } 
    return u; 
} 

// then make a call to below method form your activity's button click or 
// else 

public void facebookLogin() { 
    this.mFacebook = new Facebook(appId);// give your appId 

    if (mFacebook.isSessionValid()) { 
     new FbLoginAsync().execute(); 
    } else { 
     SessionEvents.AuthListener listener = new SessionEvents.AuthListener() { 
      @Override 
      public void onAuthSucceed() { 
       new FbLoginAsync().execute(); 
      } 

      @Override 
      public void onAuthFail(String error) { 
       showDialogCustome("Error in Facebook Login, please try again later"); 
       Log.e("onAuthFail", "onAuthFail"); 
      } 
     }; 
     SessionEvents.addAuthListener(listener); 
     mFacebook.authorize(this.activity, this.permissions, 
       Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener()); 
    } 
} 

我希望这可以解决您的问题。让我知道