我试图通过Toast显示一条简单的消息,并收到运行时异常“将消息发送到死线程上的处理程序”。试图显示Toast消息的类扩展了IntentService。该类(C2DMReceiver)实际上来自C2DM的ChromeToPhone示例。方法如下:

/**
 * 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);

    }
}

我假设由于该类扩展了IntentService,因此可以通过这种方式从此处请求一条简单的Toast消息。这不正确吗?

最佳答案

这是由于Android框架中AsyncTask中的错误所致。 AsyncTask.java具有以下代码:

private static final InternalHandler sHandler = new InternalHandler();

它希望可以在主线程上初始化它,但这不能保证,因为它将在碰巧导致该类运行其静态初始化程序的任何线程上进行初始化。我在处理程序引用工作线程的情况下重现了此问题。

导致这种情况发生的常见模式是使用IntentService类。 C2DM示例代码执行此操作。

一个简单的解决方法是将以下代码添加到应用程序的onCreate方法中:
Class.forName("android.os.AsyncTask");

这将强制在主线程中初始化AsyncTask。我在android bug数据库中对此提交了一个bug。参见http://code.google.com/p/android/issues/detail?id=20915

09-17 11:45
查看更多