Android 程序进入后台 恢复到前台

时间:2021-03-10 17:08:42

用户点击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 List<Activity> activityList;//用于关闭程序、退出登录
private List<Activity> mList;
private boolean mIsAppOnForeground;//程序在前台运行

public static synchronized CustomApplication getInstance() {
return instance;
}

@Override
public void onCreate() {
super.onCreate();
instance = this;
mContext = this.getApplicationContext();
activityList = new ArrayList<Activity>();
mList = new ArrayList<Activity>();
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();    }}