java.lang.RuntimeException: Handler (android.os.Handler) 向死线程上的 Handler 发送消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20059188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:15:17  来源:igfitidea点击:

java.lang.RuntimeException: Handler (android.os.Handler) sending message to a Handler on a dead thread

androidandroid-intentservicehandlerruntimeexception

提问by eyal

in my app I'm using IntentService for sending SMS.

在我的应用程序中,我使用 IntentService 发送短信。

    @Override
protected void onHandleIntent(Intent intent) {
    Bundle data = intent.getExtras();
    String[] recipients = null;
    String message = getString(R.string.unknown_event);
    String name = getString(R.string.app_name);
    if (data != null && data.containsKey(Constants.Services.RECIPIENTS)) {
        recipients = data.getStringArray(Constants.Services.RECIPIENTS);
        name = data.getString(Constants.Services.NAME);
        message = data.getString(Constants.Services.MESSAGE);
        for (int i = 0; i < recipients.length; i++) {
            if(!StringUtils.isNullOrEmpty(recipients[i])) {
                try {
                    Intent sendIntent = new Intent(this, SMSReceiver.class);
                    sendIntent.setAction(Constants.SMS.SEND_ACTION);
                    PendingIntent sendPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Intent deliveryIntent = new Intent(this, SMSReceiver.class);
                    deliveryIntent.setAction(Constants.SMS.DELIVERED_ACTION);
                    PendingIntent deliveryPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, deliveryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    SmsManager.getDefault().sendTextMessage(recipients[i].trim(), null, "[" + name + "] " + message, sendPendingIntent, deliveryPendingIntent);
                } catch (Exception e) {
                    Log.e(TAG, "sendTextMessage", e);
                    e.printStackTrace();
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                    MainActivity.instance.writeToLogFile(e.getMessage(), System.currentTimeMillis());                       
                }
            }
        }
    }
}

when running the app, I get the following error:

运行应用程序时,我收到以下错误:

W/MessageQueue(7180): Handler (android.os.Handler) {42586468} sending message to a Handler on a dead thread
W/MessageQueue(7180): java.lang.RuntimeException: Handler (android.os.Handler) {42586468} sending message to a Handler on a dead thread
W/MessageQueue(7180):   at android.os.MessageQueue.enqueueMessage(MessageQueue.java:294)
W/MessageQueue(7180):   at android.os.Handler.enqueueMessage(Handler.java:618)
W/MessageQueue(7180):   at android.os.Handler.sendMessageAtTime(Handler.java:587)
W/MessageQueue(7180):   at android.os.Handler.sendMessageDelayed(Handler.java:558)
W/MessageQueue(7180):   at android.os.Handler.post(Handler.java:323)
W/MessageQueue(7180):   at android.widget.Toast$TN.hide(Toast.java:367)
W/MessageQueue(7180):   at android.app.ITransientNotification$Stub.onTransact(ITransientNotification.java:55)
W/MessageQueue(7180):   at android.os.Binder.execTransact(Binder.java:351)
W/MessageQueue(7180):   at dalvik.system.NativeStart.run(Native Method)

My SMSReceiver is located in another class. How can i solve this problems? Thanks; Eyal.

我的 SMSReceiver 位于另一个类中。我该如何解决这些问题?谢谢; 艾尔。

回答by rubenlop88

The problem here is that you are creating a Toastinside a thread that is managed by the IntentService. The system will use the Handlerassociated with this thread to show and hide the Toast.

这里的问题是您正在创建一个ToastIntentService. 系统将使用Handler与此线程关联的 来显示和隐藏Toast.

First the Toastwill be shown correctly, but when the system tries to hide it, after the onHandleIntentmethod has finished, the error "sending message to a Handler on a dead thread" will be thrown because the thread on which the Toastwas created is no longer valid, and the Toastwill not disappear.

首先Toast将正确显示,但是当系统试图隐藏它时,在onHandleIntent方法完成后,将抛出错误“将消息发送到死线程上的处理程序”,因为Toast创建的线程不再有效,并且Toast不会消失。

To avoid this you should show the Toastposting a message to the Main Thread. Here's an example:

为避免这种情况,您应该Toast向主线程显示发布消息。下面是一个例子:

    // create a handler to post messages to the main thread
    Handler mHandler = new Handler(getMainLooper());
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
        }
    });

回答by Finava Vipul

Display Toaston IntentService. try this code..

IntentService上显示Toast。试试这个代码..

@Override
public void onCreate() {
    super.onCreate();
    mHandler = new Handler();
}

@Override
protected void onHandleIntent(Intent intent) {
    mHandler.post(new Runnable() {            
        @Override
        public void run() {
            Toast.makeText(MyIntentService.this, "Test", Toast.LENGTH_LONG).show();                
        }
    });
}

source :- https://stackoverflow.com/a/5420929/4565853

来源:- https://stackoverflow.com/a/5420929/4565853

回答by CodeToLife

I think you need to check a condition:

我认为你需要检查一个条件:

mHandler.getLooper().getThread().isAlive()

The application will just warn you about this error. Of course it s mostly not fatal one. But if there are many spawned usages of this handler these warnings will slow down the application.

该应用程序只会警告您有关此错误的信息。当然,它大多不是致命的。但是如果这个处理程序有很多产生的用法,这些警告会减慢应用程序的速度。