Friday, 29 June 2012

Android sending message to a Handler on a dead thread AsyncTask

When developing your Android app and you start mixing AsyncTask with BroadcastReceiver, you might see the reports of "sending a message to a Handler on a dead thread"

Having repeatedly checking my code and not finding a fault I discovered after much research the following.

AsyncTask expects to be initialised on the Main thread. This might not happen when you are using a BroadcastReceeiver.

A workaround is to ensure that AsyncTask is initialised in your main application like this:

public class YourApplication extends Application {

    @Override
    public void onCreate() {

        // workaround for http://code.google.com/p/android/issues/detail?id=20915
        try {
            Class.forName("android.os.AsyncTask");
        } catch (ClassNotFoundException e) {
        }

        super.onCreate();
    }
} 
 
and define YourApplication in your Manifest.

2 comments:

  1. Thank Rica, I appreciate the feedback.

    ReplyDelete
  2. How I have to define application in manifest?Any example please?

    ReplyDelete