android 判断当前application 是在前台还是在后台
16lz
2021-01-23
/**
*判断当前应用程序处于前台还是后台
*
* @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 常用代码备份
- [Android] 代码实现按钮/图片自旋转(中心旋转)
- android 的C++代码都加 namespace android
- Android代码混淆一定要Export Android Application,否则不起效
- Android的Location功能代码
- 第一行代码笔记之——Activity启动模式
- Android:简单联网获取网页代码
- Android 开发笔记 - Android Studio 代码模板
- android源代码下载及编译