android 判断当前application 是在前台还是在后台
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
? ? /**? ? ?*判斷當前應用程序處于前臺還是后臺
? ? ?*?
? ? ?* @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" />
下面這段代碼是我最新發(fā)現(xiàn),無需權限,妥妥滴:
/**
*?
* @param context
* @return
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.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;
}
轉載于:https://my.oschina.net/zhangjie830621/blog/109859
總結
以上是生活随笔為你收集整理的android 判断当前application 是在前台还是在后台的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 堆 和 栈的 区别(经典)
- 下一篇: neo4j——图数据库初探 - JDre