2

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Rikki Tikki Tavi
  • 3,089
  • 5
  • 43
  • 81

1 Answers1

12

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>);
}
DunClickMeBro
  • 191
  • 1
  • 4
  • thank you very much for easy and workable solution! You helped a lot! – Rikki Tikki Tavi Oct 05 '12 at 08:04
  • You might have to instantiate the handler like `new Handler(Looper.getMainLooper())` in case the service is running on different thread. – Petr Apr 01 '14 at 22:13
  • 3
    "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. – Trevor Jul 18 '14 at 20:25
  • By 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. – DunClickMeBro Jul 29 '14 at 14:52