欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android判断应用是否在前台工具类封装

程序员文章站 2022-06-16 09:45:54
闲话少说,封装的工具类如下:package com.corecmd.tcloud.tcim.utils;import android.app.ActivityManager;import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import com.corecmd.tcloud.tcim.common.Constant;im...

文章已同步更新到个人博客:www.tianshaojiao.com
闲话少说,封装的工具类如下:

package com.corecmd.tcloud.tcim.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.corecmd.tcloud.tcim.common.Constant;

import java.util.List;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote :
 * @date : 2021/3/3
 * @copyright :
 */
public class AppUtil {
    /**
     * 返回当前的应用是否处于前台显示状态
     * @param $packageName 应用包名
     * @return
     */
    public static boolean isTopActivity(Context context,String $packageName)
    {
        boolean isTop = false;
        //_context是一个保存的上下文
        ActivityManager am = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> process = am.getRunningAppProcesses();
        if(process.size() > 0) {
            for(ActivityManager.RunningAppProcessInfo processInfo : process)
            {
                if(processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
                        processInfo.processName.equals($packageName)){
                    isTop = true;
                    break;
                }
            }
        }
        return isTop;
    }

    /**
     * 取得应用程序包名
     * @param context 上下文
     * @return
     */
    public static String getAppPackageName(Context context){
        String packageName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            packageName = packageInfo.packageName;
        } catch (Exception e) {
            System.out.println("取得包名异常"+e.getMessage());
            packageName = Constant.TCIMPACKAGENAME;
        }
        return packageName;
    }
}

本文地址:https://blog.csdn.net/MasterAjoe/article/details/114319066

相关标签: android