I have a Toast
that is called from inside a Service
.
It always appears regardless of the state of the app, as designed.
How can make it appear
mparaz,
There are a number of ways to do what you want very easily. Before I do that, I'd like to address a very important flaw in your question. An App is not an Activity, and an Activity is not an App. As such, an app cannot be in the foreground or background. That is reserved only for Activities.
A quick example and then to you answer. Your Service is part of your Application. The application is loaded though the Activity is not. If your Application were not loaded, your Service could not run. I only emphasize this because it is an important philosophy in Android and understanding the correct use of these terms and the concepts that define them will make it so much easier for you in the future.
A Simple Solution
You may extend the Application object and hold a simple public flag in the class. Then you can set the flag to false anytime the activity goes to the background and true when it comes to the foreground (or vice versa, of course).
Extending the Application:
public class MyApplication extends Application
{
static public boolean uiInForeground = false;
}
Setting the flag: In your Activity...
//This may be done in onStart(), onResume(), onCreate()...
//... whereever you decide it is important.
//Note: The functions here do not include parameters (that's Eclipse's job).
public void onStart()
{//Notice the static call (no instance needed)
MyApplication.uiInForeground = true;
}
public void onPause()
{
MyApplication.uiInForeground = false;
}
In your Service (where you call the Toast)
if (MyApplication.uiInForeground)
Toast.makeText(someContext, myMsg).show();
It's really as simple as that. Oh yeah... Don't forget to tell the manifest that you are extending the Application. For your Application declaration in AndroidManifest.xml
Hope this helps,
FuzzicalLogic