Android判断应用是否在前台工具类封装
程序员文章站
2022-03-08 16:11:33
闲话少说,封装的工具类如下: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