How to create toast from IntentService? It gets stuck on the screen

后端 未结 3 926
野趣味
野趣味 2020-12-09 02:34

I\'m trying to have my IntentService show a Toast message, but when sending it from the onHandleIntent message, the toast shows but gets stuck and the screen and never leave

相关标签:
3条回答
  • 2020-12-09 03:14

    in onCreate() initialize a Handler and then post to it from your thread.

    private class DisplayToast implements Runnable{
      String mText;
    
      public DisplayToast(String text){
        mText = text;
      }
    
      public void run(){
         Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
      }
    }
    protected void onHandleIntent(Intent intent){
        ...
      mHandler.post(new DisplayToast("did something")); 
    }
    
    0 讨论(0)
  • 2020-12-09 03:24

    Use the Handle to post a Runnable which content your operation

    protected void onHandleIntent(Intent intent){
        Handler handler=new Handler(Looper.getMainLooper());
        handler.post(new Runnable(){
        public void run(){ 
            //your operation...
            Toast.makeText(getApplicationContext(), "hello world", Toast.LENGTH_SHORT).show();
        }  
    }); 
    
    0 讨论(0)
  • 2020-12-09 03:27

    Here is the full IntentService Class code demonstrating Toasts that helped me:

    package mypackage;
    
    import android.app.IntentService;
    import android.content.Intent;
    import android.os.Handler;
    import android.os.Looper;
    import android.widget.Toast;
    
    public class MyService extends IntentService {
        public MyService() { super("MyService"); }
    
        public void showToast(String message) {
            final String msg = message;
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                }
            });
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            showToast("MyService is handling intent.");
        }
    }
    
    0 讨论(0)
提交回复
热议问题