How to know if my android app is visible? How to know if my android app is visible? android android

How to know if my android app is visible?


But I would like to fire a notification using notificationManager only if the app is not currently visible, and to show an alertDialog if the timer ends while the app is in foreground.

Use an ordered broadcast, with the activity having a high-priority receiver if it is in the foreground, plus a manifest-registered receiver for the cases when it is not in the foreground.

Here is a blog post outlining this technique.

UPDATE 2018-01-04: The approach described above works, but it involves system broadcasts, which is not a great choice for most (single-process) apps. An event bus (LocalBroadcastManager, greenrobot's EventBus) can be used instead, with better performance and security. See this sample app that uses LocalBroadcastManager and this sample app that uses greenrobot's EventBus, both of which implement this pattern.


You can detect whether your app is visible or not the following way:

In all your your Activity, set:

@Overrideprotected void onResume() {    super.onResume();    myVisibilityManager.setIsVisible(true);}@Overrideprotected void onPause() {    myVisibilityManager.setIsVisible(false);    super.onPause();}

(this may lead you to define a superclass to all your activities that would implement this behaviour)

Then create a VisibilityManager (this one is very basic, you may need something more advanced):

public class VisibilityManager {    private boolean mIsVisible = false;    public void setIsVisible(boolean visible) {          mIsVisible = visible;     }    public boolean getIsVisible() {         return mIsVisible;    }}

And then, in your timer thread, when the countdown reached zero:

if (VisibilityManager.getIsVisible()) {    showAlertDialog();}else {    showNotification();}

EDIT: but I even prefer the CommonsWare's approach described here in this page. It is more elegant.


I would advise you use a Service rather than an activity in this case.

A service runs in the background and is not affected by the activity lifecycle if it is started correctly.

One important thing to remember is that when you go back to the UI, the service must explicitly call the UI thread, otherwise you will get ANR errors, as the UI thread is not threadsafe.

Please read through that document, it should help you get a better solution for what you're trying to do!

Hope this helped