一切都在標題中。是否可以在Service類中使用AsyncTask?
在官方文檔中指出,Note that services, like other application objects, run in the main thread of their hosting process
和AsyncTask只有在UIThread中執行時纔有效。
那麼有可能在Service類中使用AsyncTask?
我想這樣做,但我總是得到同樣的錯誤
05-01 18:09:25.487: ERROR/JavaBinder(270): java.lang.ExceptionInInitializerError
...
05-01 18:09:25.487: ERROR/JavaBinder(270): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我是不是做錯了什麼或者這只是不可能?
這裏是我的服務類
package com.eip.core;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class NetworkService extends Service {
private final INetwork.Stub mBinder = new INetwork.Stub() {
@Override
public int doConnect(String addr, int port) throws RemoteException {
new ConnectTask().execute("test42");
return 0;
}
};
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private class ConnectTask extends AsyncTask<String, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("OnPreExecute()", "");
}
@Override
protected Void doInBackground(String... arg0) {
Log.i("doInBackground()", "");
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i("OnPostExecute()", "");
}
}
}
嗨,它沒有違反線程規則,因爲你的服務總是在UI線程上運行,直到你不從線程分叉線程 – user1530779 2015-02-05 04:18:34
因此,上面的代碼將工作得很好,我想你在服務和意圖服務之間感到困惑,意圖服務默認在後臺線程中運行 – user1530779 2015-02-05 04:26:54