To check if Android Activity is currently running

Asked 2 years ago, Updated 2 years ago, 93 views

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

List proInfos = activityManager.getRunningAppProcesses();

for (int i = 0; i < proInfos.size(); i++) { if (proInfos.get(i).processName.equals(pakageName)) { Log.d(TAG, "Running : " + proInfos.get(i).processName); }

}

I found the same way, but I think it's a way to check the process Maybe because the service is working on the app, the log is recorded even if I close Activity.

I also found a way to change the static variable value to true/false when starting and ending Activity I don't know what's good. (There are several activities, so it's kind of weird to check all activities...)

android activity

2022-09-22 21:37

2 Answers

To verify that Activity is running (=Foreground state), see Telegram's Foreground Detector class. The principle is to use Application.ActivityLifeCallbacks to determine whether Activity is Foreground or Background as a reference count when onStart()/onStop() of Activity is called. (Note, it works even if multiple activities exist.)

https://github.com/DrKLO/Telegram/blob/a7513b3ba1923113840e78799c4c4132cc7f3116/TMessagesProj/src/main/java/org/telegram/ui/Components/ForegroundDetector.java

For example, if you have an app that receives GPS events periodically every second. To prevent battery consumption, you can stop receiving GPS events when the app goes down to the background, and if you want to receive events when it comes up to the foreground again, you can easily resolve them with the Fogreground Detector.


2022-09-22 21:37

The code you wrote above is a code that can confirm whether the process is currently active.

So just because the app goes home doesn't mean Process is dead.

To check if activity has gone down, please add the following:

I think you can check if there is topActivity instead of processName.

RunningTaskInfo running = info.get(0);        
ComponentName componentName = running.topActivity;
return cls.getName().equals(componentName.getClassName());

Reference


2022-09-22 21:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.