android 判断当前application 是在前台还是在后台
16lz
2021-12-04
/**
*判断当前应用程序处于前台还是后台
*
* @param context
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
*判断当前应用程序处于前台还是后台
*
* @param context
* @return
*/
public static boolean isApplicationBroughtToBackground(final Context context) {ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
上面这段代码是需要一个权限的:
下面这段代码是我最新发现,无需权限,妥妥滴:
/**
*
* @param context
* @return
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
Log.i(String.format("Background App:", appProcess.processName));
return true;
}else{
Log.i(String.format("Foreground App:", appProcess.processName));
return false;
}
}
}
return false;
}
更多相关文章
- Android(安卓)error:Lint found fatal errors while assembling
- 问题:plugin with id 'android' not found
- Android+Junit单元测试1
- 2011.09.09(2)——— android 桌面添加快捷方式
- android 实现类似Iphone底部消息数量提示
- android 常用代码备份
- android 的C++代码都加 namespace android
- Android--通过关键字查找短消息数据库并将匹配的信息显示
- [Android] 代码实现按钮/图片自旋转(中心旋转)