Show toast at current Activity from service
10,131
Try using a Handler. Thing about Toasts is, you have to run makeText on the UI thread, which the Service doesn't run on. A Handler allows you to post a runnable to be run on the UI thread. In this case you would initialize a Handler in your onStartCommand method.
private Handler mHandler;
@Override
onStartCommand(...) {
mHandler = new Handler();
}
private class ToastRunnable implements Runnable {
String mText;
public ToastRunnable(String text) {
mText = text;
}
@Override
public void run(){
Toast.makeText(getApplicationContext(), mText, Toast.LENGTH_SHORT).show();
}
}
private void someMethod() {
mHandler.post(new ToastRunnable(<putTextHere>);
}
Author by
Rikki Tikki Tavi
Updated on June 14, 2022Comments
-
Rikki Tikki Tavi almost 2 years
I need to show Toast at the current Activity if it come some updatings to the Service. So Service call server and if it is some updatings, I need to notificate user nevermind at which Activity he is. I try to implement it like this:
Toast.makeText(ApplicationMemory.getInstance(), "Your order "+progress+"was updated", Toast.LENGTH_LONG).show();
where
public class ApplicationMemory extends Application{ static ApplicationMemory instance; public static ApplicationMemory getInstance(){ return instance; } }
and it doesn't works. I also tried to get current Activity name with
ActivityManager am = (ActivityManager) ServiceMessages.this.getSystemService(ACTIVITY_SERVICE); List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; componentInfo.getPackageName(); Log.d("topActivity", "CURRENT Activity ::" + componentInfo.getClassName());
But don't know how to get context object from the ComponentName.
-
Rikki Tikki Tavi over 11 yearsthank you very much for easy and workable solution! You helped a lot!
-
Petr about 10 yearsYou might have to instantiate the handler like
new Handler(Looper.getMainLooper())
in case the service is running on different thread. -
Trevor almost 10 years"you have to run makeText on the UI thread, which the Service doesn't run on" is wrong. Code in a
Service
does run on the UI thread. -
DunClickMeBro almost 10 yearsBy default, it is true that Service code will run in the main thread of the host process. However, it is very common to spawn a new thread inside the service or have it run in a separate process, which I guessed Tavi's implementation might be doing.