Checking if an Android application is running in the background

前端 未结 30 2780
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  北海茫月
    2020-11-21 07:08

    I think this question should be more clear. When? Where? What is your specific situation you want to konw if your app is in background?

    I just introduce my solution in my way.
    I get this done by using the field "importance" of RunningAppProcessInfo class in every activity's onStop method in my app, which can be simply achieved by providing a BaseActivity for other activities to extend which implements the onStop method to check the value of "importance". Here is the code:

    public static boolean isAppRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
        List appProcesses = activityManager
            .getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE) {
                    return true;
                } 
            }
        }
        return false;
    }
    

提交回复
热议问题