zoukankan      html  css  js  c++  java
  • 判断app是否在后台

    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;
    }

  • 相关阅读:
    深入理解JavaScript闭包
    冒泡排序
    Objective-C中的self和super
    IOS中UIKit——UIButton的背景图像无法正常显示的原因
    IOS绘图——简单三角形
    NSDateFormatter中时间格式串的含义
    IOS屏幕布局
    IOS学习感想
    WWDC————苹果全球开发者大会
    刚开始学IOS遇到的类和方法
  • 原文地址:https://www.cnblogs.com/dongweiq/p/5938038.html
Copyright © 2011-2022 走看看