判断程序前后台方法很多,这里讲解一种最简单的方式。
继承Application ,添加registerActivityLifecycleCallbacks回调,然后读取在前台的Activity个数,大于等于1在前台,等于0在后台。
public class UVApplication extends Application {
private static UVApplication mVUApplication;
private int mActivityCount = 0;
@Override
public void onCreate() {
super.onCreate();
mVUApplication = this;
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
LogUtil.d("onActivityStarted: "+activity.getLocalClassName());
mActivityCount++;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
LogUtil.d("onActivityStopped: "+activity.getLocalClassName());
mActivityCount--;
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
public static UVApplication getVUInstance() {
return mVUApplication;
}
public int getActivityCount() {
return mActivityCount;
}
}
使用方式继承UVApplication,在AndroidManifest.xml文件引入:
<application
android:name=".MyApplication"
然后获取application,读取getActivityCount的值就可以判断。
上面的方法有个问题是如果重写了Application,会限制程序的扩展,如果需要集成其他组件用到了Application就麻烦了。
registerActivityLifecycleCallbacks源码:
public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks callback) {
synchronized (mActivityLifecycleCallbacks) {
mActivityLifecycleCallbacks.add(callback);
}
}
所以registerActivityLifecycleCallbacks函数内部对于监听的添加是每次调用都会添加新的回调函数,而不是覆盖原来的,所以只要用户传入Application,就可以利用传入的Application添加registerActivityLifecycleCallbacks监听。
public void addActivityLifecycleCallbacks(Context context) {
Application application = null;
if (context instanceof Application) {
application = ((Application) context);
} else if (context.getApplicationContext() instanceof Application) {
application = ((Application) context.getApplicationContext());
}
if (application != null) {
application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
LogUtil.d("onActivityStarted: " + activity.getLocalClassName());
mActivityCount++;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
LogUtil.d("onActivityStopped: " + activity.getLocalClassName());
mActivityCount--;
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}