I'm trying to run a asynchronous task inside the IntentService for downloading a file. However when I start the downloading thread, I get the following warning, and the process doesn't proceed.
W/MessageQueue(10371): java.lang.RuntimeException: Handler{406ee8f8} sending message to a Handler on a dead thread
I searched about this issue, and found that it's likely to have something to do with Handler and Looper of Pipeline Threading. The cause might be that the process of the thread to download a file is passed to the Handler of IntentService which dies soon after finishing its process. I know the thread should be passed to the Handler of the main thread (UI thread), not IntentService. Some people are saying that writing the following code in MainActivity class or Application class's onCreate() works, in order to pass the thread to proper Handler (Handler of main thread),
Class.forName("name.of.class.doing.asynch.task");
, but didn't work for me.
Let me give you details about my code and libraries I'm using.
- IntentService
Extending the class GCMBaseIntentService of "Google Cloud Messaging" (http://developer.android.com/guide/google/gcm/index.html). The error above occurs after Log.i(TAG, "STARTING CONNECTION") on LogCat.
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)
}
- Thread to download a file
Using "Android Asynchronous Http Client" (http://loopj.com/android-async-http/) which facilitates asynchronous http connection.
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);
}
}
Application's onCreate()
class MyApp extends Application{
@Override
onCreate(){
try {
Class.forName("com.myapp.AsynchConnector");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
How can I make this work? Please help me!