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

后端 未结 5 2291
一生所求
一生所求 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 10:46

    OnHandleIntent is called on a background thread, and any attempt to touch the UI will result in a crash. Use an Handler to post a Runnable on the UI Thread to show your toast.

    private class MyRunnable implements Runnable {
    
       final int mTextId = -1; 
       final Context mContext;
       public MyRunnable(Context c, int textId) {
           mTextId = textId;
           mContext = c;
       }
    
       @Override
       public void run() {
           Toast.makeText(mContext, 
               getString(mTextId), 
               Toast.LENGTH_SHORT).show();             
        }
    }
    
       Handler handler = new Handler();
       handler.post(new MyRunnable(this, R.string.car_opened));
    

提交回复
热议问题