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?
A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.
Steps: declare a handler in the main activity (onCreate) now create a thread from the main activity and pass the Context of that activity. now use this context in the Toast, instead of using getApplicationContext()
The Toast. makeText() method is a pre-defined method which creates a Toast object. Parameters: This method accepts three parameters: context: The first parameter is a Context object which is obtained by calling getApplicationContext().
In general, a Toast can be displayed for either 2 seconds (Toast. LENGTH_SHORT) or 3.5 seconds (Toast. LENGTH_LONG). In this article, we will show you how you could display Toast for longer or shorter in Android.
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")); }
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."); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With