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

百般思念 提交于 2019-11-29 19:42:15
rubenlop88

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

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

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

    // 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();
        }
    });
Finava Vipul

Display Toast on IntentService. try this code..

@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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!