码迷,mamicode.com
首页 > 移动开发 > 详细

判断app是否在后台

时间:2016-10-08 14:12:28      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

1、通过RunningTaskInfo类判断(需要额外权限):(测试通过5.1可用,权限名称修改

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

 

/**
     *判断当前应用程序处于前台还是后台
     */
    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;

 

    }

 

需要在AndroidMenitfest.xml文件中添加以下权限

 

 

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

 

2、通过RunningAppProcessInfo类判断(不需要额外权限)(5.1以上系统不可用): 

 

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("后台", appProcess.processName);
                          return true;
                }else{
                          Log.i("前台", appProcess.processName);
                          return false;
                }
           }
    }
    return false;
}

判断app是否在后台

标签:

原文地址:http://www.cnblogs.com/dongweiq/p/5938038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!