1. 程式人生 > >android 判斷當前application 是在前臺還是在後臺

android 判斷當前application 是在前臺還是在後臺

    /**
     *判斷當前應用程式處於前臺還是後臺
     * 
     * @param context

     * @return    

     */

    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;

    }

上面這段程式碼是需要一個許可權的:

 <uses-permission android:name="android.permission.GET_TASKS" />

下面這段程式碼是我最新發現,無需許可權,妥妥滴:

/**

* @param context
* @return
*/
public static boolean isBackground(Context context) {


ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
Log.i(String.format("Background App:", appProcess.processName));
return true;
}else{
Log.i(String.format("Foreground App:", appProcess.processName));
return false;
}
}
}
return false;
}