赞
踩
用户点击home键程序进入后台,此时用户再点击图标或在最近运行程序中打开程序,程序进入前台,有没有一个简单方便的方法来实现监听状态变化呢?
有人说监听home键,也有人说所有Activity继承一个BaseActivity,我的方法是通过Application里的registerActivityLifecycleCallbacks,
ActivityLifecycleCallbacks可以监听程序里所有Activity的生命周期方法,Activity执行onStart时存入List,onStop时从List中移除,
当List的size为0时说明程序进入后台。
我这里还有一个LIst用来存放所有没被finish掉的Activity,onCreate时存入,onDestory时移除,用于关闭程序或退出登录时批量关闭Activity。直接看代码吧
public class CustomApplication extends MultiDexApplication {
Context mContext;
private static CustomApplication instance;
public static ListactivityList;//用于关闭程序、退出登录
private ListmList;
private boolean mIsAppOnForeground;//程序在前台运行
public static synchronized CustomApplication getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
mContext = this.getApplicationContext();
activityList = new ArrayList();
mList = new ArrayList();
mIsAppOnForeground = false;
JodaTimeAndroid.init(this);
initImageLoader();
this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
if (!activityList.contains(activity)) {
activityList.add(activity);
}
}
@Override
public void onActivityStarted(Activity activity) {
if (!mList.contains(activity)) {
mList.add(activity);
}
if (!mIsAppOnForeground) {
updateJpushInfo();
mIsAppOnForeground = true;
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
if (mList.contains(activity)) {
mList.remove(activity);
}
if (mList.size() == 0) {
mIsAppOnForeground = false;
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if (activityList.contains(activity)) {
activityList.remove(activity);
}
}
});
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。