Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if my Android app is displayed?

Tags:

android

I have an Android app with a service that runs in the background doing various client/server connections. How can I check in my running service if any screen from my app is displayed?

like image 869
Lysandus Avatar asked Nov 19 '25 08:11

Lysandus


1 Answers

You can get the list of running processes and check if yours is in foreground with the following code:

ActivityManager actMngr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
    if (getPackageName().equals(pi.processName)) {

        boolean inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
    }
}

Check more at http://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo.html

like image 149
pandre Avatar answered Nov 21 '25 23:11

pandre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!