Android判断当前App是在前台还是在后台
作者:xx326664162 时间:2022-09-20 10:37:49
本文实例为大家分享了Android判断当前App状态的具体实现代码,供大家参考,具体内容如下
第一种:
/**
*判断当前应用程序处于前台还是后台
*
* @param context
* @return
*/
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;
}
上面这段代码是需要一个权限的:
< uses-permission Android:name=”android.permission.GET_TASKS” />
第二种:
下面这段代码是我最新发现,无需权限,妥妥滴:
不过我稍微做了调整,后台分为:service后台和activity后台,这里认为不是前台的都认为后台。
•service运行在后台,appProcess.importance = IMPORTANCE_SERVICE,
•没有service运行的后台,
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
System.out.print(String.format("Foreground App:", appProcess.processName));
return false;
}else{
System.out.print("Background App:"+appProcess.processName);
return true;
}
}
}
return false;
}
标签:android,app,后台,前台
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#判断多个文本框是否为空的方法
2022-05-12 23:05:32
解析Java的Hibernate框架中的持久化类和映射文件
2023-08-19 15:00:05
详解java模板和回调机制
2023-08-13 15:33:46
解决Spring在Thread中注入Bean无效的问题
2022-06-26 13:03:59
Android模拟器对应的电脑快捷键说明
2022-11-09 17:44:07
eclipse springboot工程打war包方法及再Tomcat中运行的方法
2023-04-14 09:21:40
![](https://img.aspxhome.com/file/2023/9/78349_0s.png)
Android 滑动监听的实例详解
2023-10-28 14:32:32
![](https://img.aspxhome.com/file/2023/9/91049_0s.png)
如何在XML中定义菜单
2023-08-08 11:49:33
![](https://img.aspxhome.com/file/2023/2/108262_0s.jpg)
MyBatis多表关联查询的实现示例
2023-07-06 06:26:49
![](https://img.aspxhome.com/file/2023/8/88748_0s.jpg)
mybatisPlus条件构造器常用方法小结
2023-12-16 07:04:09
unity实现贴图矩阵运算(旋转平移缩放)
2022-07-27 13:53:41
C# 禁用鼠标中间键的方法
2022-01-24 04:17:24
C#创建一个Word并打开的方法
2022-08-04 23:33:13
SpringMVC实现多文件上传
2023-10-12 16:49:15
![](https://img.aspxhome.com/file/2023/9/67999_0s.jpg)
C# 基于TCP 实现扫描指定ip端口的方式示例
2021-11-28 07:55:24
![](https://img.aspxhome.com/file/2023/3/96293_0s.png)
Android BadTokenException异常解决案例详解
2022-04-08 16:10:59
![](https://img.aspxhome.com/file/2023/9/88659_0s.jpg)
详细了解C# 枚举与位枚举
2023-02-19 17:36:57
![](https://img.aspxhome.com/file/2023/3/113723_0s.png)
Java深入浅出理解快速排序以及优化方式
2023-01-17 13:50:44
![](https://img.aspxhome.com/file/2023/9/69319_0s.jpg)
Java项目开发命名规范(动力节点Java学院整理)
2021-06-24 07:16:56
java中Integer包装类装箱的一个细节详解
2023-09-24 18:35:32