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

3

25

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 leaved. I'm guessing its because the onHandleIntent method does not happen on the main service thread, but how can I move it?

Has anyone has this issue and solved it?

Nutbrown answered 17/10, 2010 at 21:34 Comment(1)
Possible duplicate of Toast created in an IntentService never goes awayBronwyn
U
34

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")); 
}
Uxmal answered 17/10, 2010 at 23:44 Comment(5)
What is your mContext initialized to?Cogon
It is a reference to the service.Uxmal
the toast made this way won't go away. is there anything I should add except the code above?Irritation
@Irritation that is an interesting bug, you can always keep a reference to the toast and call its cancel methodUxmal
@AvinashR to combat that issue, just use the Handler constructor that takes a Looper. mHandler = new Handler(Looper.getMainLooper());Uxmal
C
5

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.");
    }
}
Caneghem answered 16/1, 2016 at 22:6 Comment(2)
is not possible to create a Toast using an Application-Context ... you need an activity to do that kind of stuff ...Proctor
@Proctor I provided a real-life working code snippet.Caneghem
O
3

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();
    }  
}); 
Overtrick answered 4/2, 2015 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.