Show toast at current Activity from service

2019-01-26 23:25发布

问题:

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.

回答1:


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>);
}