首页 > 系统 > Android > 正文

Android判断当前应用程序处于前台还是后台的两种方法

2020-04-11 11:58:21
字体:
来源:转载
供稿:网友

1、通过RunningTaskInfo类判断(需要额外权限):

复制代码 代码如下:

/**
     *判断当前应用程序处于前台还是后台
     */
    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类判断(不需要额外权限):

复制代码 代码如下:

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表