Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast "sending message to a Handler on a dead thread"

Tags:

I'm trying to display a simple message via Toast, and am getting a RunTime Exception "sending message to a Handler on a dead thread". The class that is trying to show the Toast message extends IntentService. The class (C2DMReceiver) actually comes from the ChromeToPhone example for C2DM. Here is the method:

/**
 * Called when a cloud message has been received.
 */
@Override
public void onMessage(Context context, Intent intent) {
    Log.i(LOG_TAG, "A message notification has occured with the cloud.");

        Log.i(LOG_TAG, "Showing toast message of the broadcast...");
        Toast toast = Toast.makeText(context, "Some text", Toast.LENGTH_LONG);
        toast.show();

        Log.i(LOG_TAG, "Sending notification of the broadcast...");
        LauncherUtils.generateNotification(this, "this is where the text would go.", "Broadcast", intent);

    }
}

I assumed since the class extends IntentService that it would be possible to request a simple Toast message from here in this manner. Isn't this correct?

like image 536
John Avatar asked Dec 14 '10 19:12

John


1 Answers

This is due to a bug in AsyncTask in the Android framework. AsyncTask.java has the following code:

private static final InternalHandler sHandler = new InternalHandler();

It expects this to be initialized on the main thread, but that is not guaranteed since it will be initialized on whichever thread happens to cause the class to run its static initializers. I reproduced this issue where the Handler references a worker thread.

A common pattern that causes this to happen is using the class IntentService. The C2DM sample code does this.

A simple workaround is to add the following code to the application's onCreate method:

Class.forName("android.os.AsyncTask");

This will force AsyncTask to be initialized in the main thread. I filed a bug on this in the android bug database. See http://code.google.com/p/android/issues/detail?id=20915.

like image 150
Jonathan Perlow Avatar answered Sep 20 '22 18:09

Jonathan Perlow