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 only when my app is in the foreground, and not when other apps are in front? That is, without moving it to Activity code.
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:
Setting the flag: In your Activity…
In your Service (where you call the Toast)
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