当前位置:   article > 正文

android 重新进入前台,Android 程序进入后台 恢复到前台

android 切后台再切回前台返回启动界面

用户点击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();

}

}

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读