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?
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.