app在前台还是后台的判断有很多种,如:
1.在BaseActivity中对Activity的进行保存管理,可以通过根据当前的所有Activity的状态来判断应用是否是在前台显示。
2.在application中注册registerActivityLifecycleCallbacks()的回调,通过回调来判断是否在前台
public class MyApp extends Application {
private static final String TAG = "TEST_APP";
private static int mActivityCount;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
mActivityCount++;
if(mActivityCount == 1) {
Log.e(TAG, "后台->前台");
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
mActivityCount--;
if(mActivityCount == 0) {
Log.e(TAG, "前台->后台");
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
}
3.通过获取系统ActivityManager来判断。
4.其他方法
新增一个方法
使用LifecycleObserver来获取对应生命周期的回调,从而判断是前台还是后台
public class ProcessLifecycleObserver implements LifecycleObserver {
private static final String TAG = LogHelper.makeLogTag(ProcessLifecycleObserver.class);
public ProcessLifecycleObserver() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onProcessCreate() {
LogHelper.d(TAG, "onProcessCreate: ");
}
/**
* 进入前台
*/
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnterForeground() {
Log.e(TAG, "onEnterForeground: ");
}
/**
* 进入后台
*/
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnterBackground() {
Log.e(TAG, "onEnterBackground: ");
}
}
在项目的application中注册
public class ComicApps extends Application {
@Override
public void onCreate() {
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ProcessLifecycleObserver());
}
}