1

I want to check if my app is running on a background mode.

The problem is that i have many activities(list activities, map activities etc.). Initially I have tried in the life cycle's resume and pause(or the onUserLeaveHint) methods to set a static boolean as true or false and work with this way. But this obviously can't work because when I move from one activity to another, the previous one get paused.

Also, I've read here on stackoverflow that the getRunningTasks() should be used only for debugging purposes. I did a huge research but I can't find a solution. All I want to do is to be able to detect if a the app is running on a background. Can anyone propose me a way, or express any thought on how can I do that?

Reno
  • 33,594
  • 11
  • 89
  • 102
Alex Dowining
  • 980
  • 4
  • 19
  • 41

3 Answers3

2

You can try the same mechanism (a boolean attribute) but on application side rather than activity side. Create a class which extends Application, declare it in the manifest file under <application android:name=YourClassApp>.

EDIT: I assume you know that activities aren't intended for background processing, if not you should take a look at the Services.

tbruyelle
  • 12,895
  • 9
  • 60
  • 74
1

I don't know if this will help but you can use

getApplicaton().registerActivityLifecycleCallbacks(yourClass);

To get a birds eye view of how your activities are displayed in the FG. (For older s/w you can use this)


If your Application has a Service you could have a static get/set which accesses a static variable. Do not do this in Activities though, it causes mem leaks.

But realistically speaking there is no tidy way of tracking if your application is running or not.

Community
  • 1
  • 1
Reno
  • 33,594
  • 11
  • 89
  • 102
0

I had the same problemen when overwriting the Firebase push messaging default behavior (show notifications only when in the background) I checked how Firebase did this by looking in the .class file com.google.firebase.messaging.zzb:53 (firebase-messaging:19.0.1) which appears to us getRunningAppProcesses. Mind you FireBase is created by Google them self. So I'm assuming it's pretty save to use. Cleaned up version:

List<ActivityManager.RunningAppProcessInfo> runningApps;            
boolean isInForeground =false;
        if ((runningApps = ((ActivityManager)this.getApplication().getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses()) != null) {
            Iterator runningApp = runningApps.iterator();
            int myPid = Process.myPid();
            while(runningApp.hasNext()) {
                ActivityManager.RunningAppProcessInfo processInfo;
                if ((processInfo = (ActivityManager.RunningAppProcessInfo)runningApp.next()).pid == myPid) {
                    isInForeground = processInfo.importance == 100;
                    break;
                }
            }
        }
IanZ
  • 31
  • 2