/**
     *判断当前应用程序处于前台还是后台
     * 
     * @param context

     * @return    

     */

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

    }

上面这段代码是需要一个权限的:

 


下面这段代码是我最新发现,无需权限,妥妥滴:

/**

* @param context
* @return
*/
public static boolean isBackground(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_BACKGROUND) {
Log.i(String.format("Background App:", appProcess.processName));
return true;
}else{
Log.i(String.format("Foreground App:", appProcess.processName));
return false;
}
}
}
return false;
}




更多相关文章

  1. Android(安卓)error:Lint found fatal errors while assembling
  2. 问题:plugin with id 'android' not found
  3. Android+Junit单元测试1
  4. 2011.09.09(2)——— android 桌面添加快捷方式
  5. android 实现类似Iphone底部消息数量提示
  6. android 常用代码备份
  7. android 的C++代码都加 namespace android
  8. Android--通过关键字查找短消息数据库并将匹配的信息显示
  9. [Android] 代码实现按钮/图片自旋转(中心旋转)

随机推荐

  1. 【Android笔记】Activity涉及界面全屏的
  2. ?attr , ?android:attr 解析
  3. Android.9图片讲解(二)
  4. Activity学习(二):Activity的启动模式(转载)
  5. Android(安卓)下的 makefile 组织结构
  6. Android判断TextView是否超出加省略号
  7. Android随笔--短小精悍的代码段(持续更新)
  8. 新浪微博请求数据出错(Android(安卓)Volle
  9. Android 8.0 通知显示
  10. cts vts 介绍