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以上,可以使用ActivityLifecycle
if (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; } }