How to display Toast from a Service after main Activity finishes?

后端 未结 5 2301
一生所求
一生所求 2020-12-14 10:22

UPDATE: I don\'t agree that this is a duplicate - because I am seeking for a way to exit the main app and still show a Toast from the service.

In a

5条回答
  •  忘掉有多难
    2020-12-14 11:04

    OnHandleIntent will run in a differant Thread so you are showing Toast in a thread which is not allowed in android

    so change your code like this

    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
    
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), 
                           getString(R.string.car_opened), 
                           Toast.LENGTH_SHORT).show();              
        }
    });
    

    From this dead thread in service

    IntentService will create a thread to handle the new intent, and terminated it immediately once the task has done. So, the Toast will be out of controlled by a dead thread.

    You should see some exceptions in the console when the toast showing on the screen.

提交回复
热议问题