我正在尝试在 IntentService 中运行异步任务以下载文件。但是,当我启动下载线程时,我收到以下警告,并且该过程不会继续。
W/MessageQueue(10371): java.lang.RuntimeException: Handler{406ee8f8} sending message to a Handler on a dead thread
我搜索了一下这个问题,发现它很可能与Pipeline Threading的Handler和Looper有关。原因可能是线程下载文件的过程被传递给 IntentService 的处理程序,该处理程序在完成其过程后很快就死了。我知道线程应该传递给主线程(UI线程)的Handler,而不是IntentService。有人说在 MainActivity 类或 Application 类的 onCreate() 中编写以下代码是可行的,以便将线程传递给适当的 Handler(主线程的 Handler),
Class.forName("name.of.class.doing.asynch.task");
,但对我不起作用。
让我详细介绍一下我正在使用的代码和库。
- 意向服务
扩展“Google Cloud Messaging”的类 GCMBaseIntentService (http://developer.android.com/guide/google/gcm/index.html)。上面的错误发生在 LogCat 上的 Log.i(TAG, "STARTING CONNECTION") 之后。
public class GCMIntentService extends GCMBaseIntentService{
public GCMIntentService() {
super(Environment.GCM_SENDER_ID);
}
@Override
protected void onMessage(Context context, Intent intent) {
String[] allowedContentTypes = new String[] { "image/jpeg" };
Log.i(TAG, "STARTING CONNECTION");
AsynchConnector.getForBinaryResponse("MY_URL", new BinaryHttpResponseHandler(allowedContentTypes){
@Override
public void onSuccess(byte[] imageData) {
Log.i(TAG, "SUCCESS!!");
});
}
(... @Override methods follows)
}
- 线程下载文件
使用有助于异步 http 连接的“Android 异步 Http 客户端”(http://loopj.com/android-async-http/)。
public class AsynchConnector{
private static final String BASE_URL = Environment.SERVER_URL;
private static AsyncHttpClient client = new AsyncHttpClient();
public static void getForBinaryResponse(String url, BinaryHttpResponseHandler binaryHttpResponseHandler){
client.get(getAbsoluteUrl(url), binaryHttpResponseHandler);
}
}
应用程序的 onCreate()
class MyApp extends Application{
@Override
onCreate(){
try {
Class.forName("com.myapp.AsynchConnector");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
我怎样才能使这项工作?请帮我!