轉載請注明出處:http://www.reibang.com/p/58fc6b1f6f54
本文出自Shawpoo的簡書
我的博客:CSDN博客
在日常的APP開發(fā)中始藕,為了對APP中所有的Activity進行管理,所以統(tǒng)一放在Stack中處理。
- 創(chuàng)建AppManager:
public class AppManager {
public static Stack<Activity> getActivityStack() {
return activityStack;
}
private static Stack<Activity> activityStack;
private static AppManager instance;
private AppManager() {
}
/**
* 單一實例
*/
public static AppManager getInstance() {
if (instance == null) {
instance = new AppManager();
}
return instance;
}
/**
* 添加Activity到堆棧
*/
public void addActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<>();
}
activityStack.add(activity);
}
/**
* 獲取棧頂Activity(堆棧中最后一個壓入的)
*/
public Activity getTopActivity() {
return activityStack.lastElement();
}
/**
* 結束棧頂Activity(堆棧中最后一個壓入的)
*/
public void finishTopActivity() {
Activity activity = activityStack.lastElement();
finishActivity(activity);
}
/**
* 結束指定類名的Activity
*
* @param cls
*/
public void finishActivity(Class<?> cls) {
Iterator iterator = activityStack.iterator();
while (iterator.hasNext()) {
Activity activity = (Activity) iterator.next();
if (activity.getClass().equals(cls)) {
iterator.remove();
activity.finish();
}
}
}
/**
* 結束所有Activity
*/
@SuppressWarnings("WeakerAccess")
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}
/**
* 退出應用程序
*/
public void appExit() {
try {
finishAllActivity();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
} catch (Exception e) {
}
}
/**
* 結束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
activity = null;
}
}
/**
* 得到指定類名的Activity
*/
public Activity getActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
return activity;
}
}
return null;
}
}
- 使用:為了進行統(tǒng)一處理,我們可以寫在BaseActivity中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
AppManager.getInstance().addActivity(this); //添加到棧中
}
@Override
protected void onDestroy() {
super.onDestroy();
AppManager.getInstance().finishActivity(this); //從棧中移除
}