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

后端 未结 3 1828
不思量自难忘°
不思量自难忘° 2020-12-12 14:48

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

    @Override
protected void onHandleIntent(Intent intent) {
    Bundle data = intent.getExtras();
    St         


        
相关标签:
3条回答
  • 2020-12-12 15:16

    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();
            }
        });
    
    0 讨论(0)
  • 2020-12-12 15:24

    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.

    0 讨论(0)
  • 2020-12-12 15:26

    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

    0 讨论(0)
提交回复
热议问题