我從IntentService進行網絡調用,但仍然收到NetworkOnMainThreadException。我的理解是IntentService總是在一個工作線程上運行,所以我很驚訝地看到這一點。關鍵的一點可能是我的IntentService正在調用執行網絡調用的靜態助手類。靜態輔助類在我的主Application類中實例化。IntentService中的NetworkOnMainThreadException
我認爲這仍然會在IntentService的工作線程上執行。我錯過了什麼?
老實說,我更喜歡關於快速代碼修復的討論。但是,如果需要的代碼,應提供代碼:
//MyApplication.java
public class MyApplication extends Application{
private static NetworkUtils utils;
@Override
public void onCreate() {
super.onCreate();
utils = new NetworkUtils(this);
...
}
...
}
//NetworkUtils.java
public class NetworkUtils {
private static Context context;
private static final Gson gson = new Gson();
public NetworkUtils(Context context) {
this.context = context;
}
public static final DataResponse login(String email, String password) {
//*** NetworkOnMainThreadException OCCURS HERE ***
DataResponse response = HttpConnection.put(url, json);
...
return response;
}
...
}
//LoginService.java
public class LoginService extends IntentService {
public LoginService() {
super("LoginService");
}
@Override
public void onStart(Intent intent, int startId) {
onHandleIntent(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle bundle = new Bundle();
DataResponse response = NetworkUtils.login(email, password);
...
bundle.putBoolean(MyConstants.ExtraKeys.LOGGED, response.success);
MainApplication.getApplicationInstance().sendBroadCast(MyConstants.Actions.LOGIN, bundle);
}
}
//LoginActivity.java
public class LoginActivity extends ActionBarActivity implements IDialogClickListener {
...
public void onLoginButtonPressed() {
Intent intent = new Intent(MainApplication.getApplicationInstance(), LoginService.class);
this.startService(intent);
}
}
此外,logcat的:
> 04-01 18:20:41.048: VERBOSE/com.foo.foo(28942):
> com.foo.foo.network.HttpConnection.execute - METHOD: PUT
> 04-01 18:20:41.068: ERROR/com.foo.foo(28942):
> com.foo.foo.social.NetworkUtils.login - class
> android.os.NetworkOnMainThreadException: null
> 04-01 18:20:41.169: DEBUG/com.foo.foo(28942):
> com.foo.foo.MainActivity$MyReceiver.onReceive - BROADCAST RECEIVED:
> [email protected] - Intent { act=com.foo.foo.login
> dat=com.foo.foo.scheme://data/1364854841079 (has extras) }
> 04-01 18:20:41.169: INFO/com.foo.foo(28942):
> com.foo.foo.activity.LoginActivity.setData - ACTION: com.foo.foo.login
> - ISERROR: true
SOLUTION
根本的問題是遺留代碼位是在呼喚onHandleIntent
明確。在上述LoginService.java:
@Override
public void onStart(Intent intent, int startId) {
onHandleIntent(intent);
}
這是造成onHandleIntent代碼給主線程上運行,因爲它是被從調用onStart事件(這顯然對主線程中運行)調用。
你錯過了一些你的代碼,所以我們可以看到發生了什麼。請發佈一些代碼,logcat輸出,並指向錯誤來自的行。 – MCeley