【Android判断App是否在前台运行】冲天香阵透长安,满城尽带黄金甲。这篇文章主要讲述Android判断App是否在前台运行相关的知识,希望能为你提供帮助。
版权声明:本文为博主原创文章,未经博主允许不得转载。//当前应用是否处于前台 private boolean isForeground(Context context) { if (context != null) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List< ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo processInfo: processes) { if (processInfo.processName.equals(context.getPackageName())) { if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } } } return false; }可以根据importance的不同来判断前台或后台 RunningAppProcessInfo 里面的常量IMOPORTANCE就是上面所说的前台后台,其实IMOPORTANCE是表示这个app进程的重要性,因为系统回收时候,会根据IMOPORTANCE来回收进程的。具体可以去看文档。。public static final int IMPORTANCE_BACKGROUND = 400//后台 public static final int IMPORTANCE_EMPTY = 500//空进程 public static final int IMPORTANCE_FOREGROUND = 100//在屏幕最前端、可获取到焦点 可理解为Activity生命周期的OnResume(); public static final int IMPORTANCE_SERVICE = 300//在服务中 public static final int IMPORTANCE_VISIBLE = 200//在屏幕前端、获取不到焦点可理解为Activity生命周期的OnStart(); 但上面的方法有的机型不支持,下面这个方法还是比较靠谱的,但需要一个权限 < uses-permission android:name =“android.permission.GET_TASKS” /> //当前应用是否处于前台 private boolean isForeground(Context context) { if (context != null) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ComponentName cn = am.getRunningTasks(1).get(0).topActivity; String currentPackageName = cn.getPackageName(); if (!TextUtils.isEmpty(currentPackageName) & & currentPackageName.equals(context.getPackageName())) { return true; } return false; } return false; }版本4.0以上,可以使用ActivityLifecycleif (Build.VERSION.SDK_INT > = 14) { lifecycle = new SimpleActivityLifecycle(); registerActivityLifecycleCallbacks(lifecycle); public class SimpleActivityLifecycle implements Application.ActivityLifecycleCallbacks {private boolean isForeground = false; //应用是否处于前端@Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}@Override public void onActivityStarted(Activity activity) {}@Override public void onActivityResumed(Activity activity) { isForeground = true; }@Override public void onActivityPaused(Activity activity) { isForeground = false; }@Override public void onActivityStopped(Activity activity) {}@Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}@Override public void onActivityDestroyed(Activity activity) {}public boolean isForeground() { return isForeground; } }
推荐阅读
- Android中Alarm的机制
- Android控件onClick事件
- mongodb与其它数据库的比较(它们有什么区别())
- 在Ubuntu上安装MongoDB(如何在Ubuntu中安装MongoDB())
- Redis与MongoDB比较(Redis与MongoDB有什么区别())
- 什么是MongoDB中的insertOne方法(用法详细指南)
- SQLite中的日期和时间类型和函数是什么()
- 如何在SQLite中使用PRIMARY KEY主键(详细介绍)
- 如何在Linux上安装Microsoft Office(详细指南)