Check application is minimized/background

2019-09-06 06:54发布

I am so surprised!

Because not able identify application currently in foreground or background,

when i pressed home button and my application is not in foreground. then after i have used to check application running in foreground or not.

public boolean isAppOnForeground()
    {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) { return false; }
        final String packageName = context.getPackageName();
        for (RunningAppProcessInfo appProcess : appProcesses)
        {
            if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; }
        }
        return false;

    }

it will returns always true even if my application actually not in foreground.

Note: My application have 2 services, 1 service will be canceled when application is removed from recent task list( that i have achieved.) 2 service will be canceled when application goes in background. (that is check wifi signal strength.)

how to know app is foreground or background?

how to stop service when application is not in foreground?

2条回答
霸刀☆藐视天下
2楼-- · 2019-09-06 07:08

Rely on Activity callback methods, such as onPause(), onStop() and onResume(), that will give you hints on the current state of Activity. The Activity reference gives a very broad explanation of every of those methods.

查看更多
做个烂人
3楼-- · 2019-09-06 07:23

try handling onpause() event of activity class. Onpause is called when activity goes out of focus.

查看更多
登录 后发表回答