本文实例讲述了Android编程判断当前应用是否在后台运行的方法。分享给大家供大家参考,具体如下:
/** 判断程序是否在后台运行 */ public static boolean isRunBackground(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) { // 表明程序在后台运行 return true; } else { return false; } } } return false; } /** 判断程序是否在前台运行(当前运行的程序) */ public boolean isRunForeground() { ActivityManager activityManager = (ActivityManager) getApplicationContext() .getSystemService(Context.ACTIVITY_SERVICE); String packageName = getApplicationContext().getPackageName(); List<RunningAppProcessInfo> appProcesses = activityManager .getRunningAppProcesses(); if (appProcesses == null) return false; for (RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true;// 程序运行在前台 } } return false; }
更多关于Android相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》
希望本文所述对大家Android程序设计有所帮助。
您可能感兴趣的文章: