先创建一个activity集合,如下:
/**
* 维护Activity 的list
*/
private static List<Activity> mActivitys = Collections.synchronizedList(new LinkedList<Activity>());
然后通过application自带的方法获取当前activity,加入到集合中,如下:
注意一下:下面这个方法要在application的onCreate()方法里面调用
**
* 描述:注册界面的生命周期,也可以
* 时间:2017/5/11
*/
private void registerActivityLifeCallback() {
registerActivityLifecycleCallbacks(new MyActivityLifeCycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mActivitys.add(activity);
}
@Override
public void onActivityDestroyed(Activity activity) {
mActivitys.remove(activity);
}
});
}
获取activity的数量
/**
* 获取acitivity数量
* @return
*/
public static int getActivityCount() {
return mActivitys.size();
}
关闭除了MainActivity的其他activity
public static void closeActivityExceptMain() {
for (Activity ac : mActivitys) {
if (ac != null && !(ac instanceof MainActivity)) {
ac.onBackPressed();
}
}
}
关闭所有activity
/**
* 关闭所有Activity
*/
public static void closeAllActivity() {
for (Activity ac : mActivitys) {
if (ac != null) {
ac.finish();
ac.overridePendingTransition(0, R.anim.slide_right_out);
}
}
}
获取到当前activity
/**
* 描述:获取当前Activity
* 时间:2017/5/11
*/
public static Activity currentActivity() {
if (mActivitys == null || mActivitys.isEmpty()) {
return null;
}
Activity activity = mActivitys.get(mActivitys.size() - 1);
return activity;
}