android 判断app是否在前台,Android 判断app是否在前台运行
方法一:使用ActivityLifecycleCallbacksandroid 在从sdk14 开始为我们提供了一个新的api 用于检测app 中activity 的生命周期,我们可以直接使用。publicinterfaceActivityLifecycleCallbacks{voidonActivityCreated(Activity activity, Bundle savedInstance
方法一:使用ActivityLifecycleCallbacks
android 在从sdk14 开始为我们提供了一个新的api 用于检测app 中activity 的生命周期,我们可以直接使用。
publicinterfaceActivityLifecycleCallbacks{voidonActivityCreated(Activity activity, Bundle savedInstanceState);voidonActivityStarted(Activity activity);voidonActivityResumed(Activity activity);voidonActivityPaused(Activity activity);voidonActivityStopped(Activity activity);voidonActivitySaveInstanceState(Activity activity, Bundle outState);voidonActivityDestroyed(Activity activity); }
根据 Activity 的生命周期,知道onStart() 一般表示一个Activity 处于前台,onStop() 一般表示Activity在后台不可见。所以我们设置一个int refCount 变量, onActivityStarted 的时候refCount++, onActivityStopped的时候refCount--。当onActivityStopped之后如果refCount == 0 了。那么表示我们的app里面没有处于onStart的Activity 了,
也就相当于 app 已经处于后台了。
classActivityLifecycleListenerimplementsActivityLifecycleCallbacks{privateintrefCount =0;@OverridepublicvoidonActivityCreated(Activity activity, Bundle savedInstanceState){ }@OverridepublicvoidonActivityStarted(Activity activity){ refCount++; }@OverridepublicvoidonActivityResumed(Activity activity){ }@OverridepublicvoidonActivityPaused(Activity activity){ }@OverridepublicvoidonActivityStopped(Activity activity){ refCount--;if(refCount ==0){ setAppGoBackGround(true); } }@OverridepublicvoidonActivitySaveInstanceState(Activity activity, Bundle outState){ }@OverridepublicvoidonActivityDestroyed(Activity activity){ } }
然后在app 里面的 Application onCreate()方法注册即可:
registerActivityLifecycleCallbacks(newActivityLifecycleListener());
方法二:
publicstaticbooleanisBackground(Context context){ ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List appProcesses = activityManager .getRunningAppProcesses();for(RunningAppProcessInfo appProcess : appProcesses) {if(appProcess.processName.equals(context.getPackageName())) {/*
BACKGROUND=400 EMPTY=500 FOREGROUND=100
GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
*/Log.i(context.getPackageName(),"此appimportace ="+ appProcess.importance +",context.getClass().getName()="+ context.getClass().getName());if(appProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { Log.i(context.getPackageName(),"处于后台"+ appProcess.processName);returntrue; }else{ Log.i(context.getPackageName(),"处于前台"+ appProcess.processName);returnfalse; } } }returnfalse; }
作者:黄海佳
链接:https://www.jianshu.com/p/2e82d4747bdf
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
更多推荐
所有评论(0)