You can detect currently foreground/background application with ActivityManager. getRunningAppProcesses() which returns a list of RunningAppProcessInfo records. To determine if your application is on the foreground check RunningAppProcessInfo.
Read moreHow do I run an Android app in the background?
You can allow a certain app to run in the background by going to Settings > Apps & notifications > Advanced > Special app access > Battery optimization . This will initially show you the apps which are Not Optimized – that is, the ones that can run in the background even while the phone is sleeping.
Read moreHow do I keep apps from running in the background on Android?
Stop Apps From Running in the Background on Android
Read moreWhat is Android alarm Manager explain with an example?
Introduction to Android AlarmManager. Android AlarmManager is a class that provides access to alarm services of the system . Through this, it lets us schedule the application to run at a particular time. As soon as the alarm goes off, the system broadcasts the intent registered for it.
Read moreHow do you set an alarm app on Android?
I have included the source code below.
Read more