Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if my android app is visible?

I have a timer that start a notification when it ends. 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.

I've already tried with this :

ActivityManager actMngr = (ActivityManager) ValeoMobileApplication.getContext().getSystemService(Activity.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
Tools.log("TimerBroadcastReceiver", "onReceive", "All running processes are listed below :");
for (RunningAppProcessInfo pi : runningAppProcesses) {
    //Check pi.processName and do your stuff
    //also check pi importance - check if process is in foreground or background
    Tools.log("TimerBroadcastReceiver", "onReceive", pi.processName + " importance = "+pi.importance);
    if(pi.processName.equalsIgnoreCase("MY_APP_PROCESS_NAME")){
        if (pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            isApplicationInForeground = true;
        }
    }
}

But it seems that it doesn't matter if the app is foreground or not. How can I do this?

like image 820
PhilippeAuriach Avatar asked Jul 27 '11 15:07

PhilippeAuriach


People also ask

How do I know if my application is on foreground or background?

It's very easy to detect when an Activity goes background/foreground just by listening to the lifecycle events, onStop() and onStart() of that Activity.

How do I know if my activity is visible?

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not.


1 Answers

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.

like image 105
CommonsWare Avatar answered Oct 07 '22 20:10

CommonsWare