Toast created in an IntentService never goes away

后端 未结 6 596
北海茫月
北海茫月 2020-11-28 10:53

I have an IntentService that downloads some files. The problem is that I create a Toast inside the IntentService like this

Toast.makeText(getApplicationCont         


        
6条回答
  •  我在风中等你
    2020-11-28 11:35

    The problem is that IntentService is not running on the main application thread. you need to obtain a Handler for the main thread (in onCreate()) and post the Toast to it as a Runnable.

    the following code should do the trick:

    @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, "Hello Toast!", Toast.LENGTH_LONG).show();                
            }
        });
    }
    

提交回复
热议问题