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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With