需求:界面A跳转到界面B,之后再跳转到界面A,此时需要销毁第一次创建的界面A,以此类推….
思路:(在每次创建当前Activity的时候销毁前部的activity即可,然后在添加当前activity的引用)
编写ActivityManagement的界面控制管理器
package com.lzyc.ybtappcal.app;
import android.support.v4.app.FragmentActivity;
import java.util.LinkedList;
/**
* 界面控制管理类
* package_name com.lzyc.ybtappcal.app
*/
public class ActivityManagement {
private static ActivityManagement instance;
private static LinkedList<FragmentActivity> activityList;
private static LinkedList<FragmentActivity> activityListRegister;
private static LinkedList<FragmentActivity> activityListCapture;
public ActivityManagement(){
if(activityList==null){
activityList=new LinkedList<FragmentActivity>();
}
if(activityListRegister==null){
activityListRegister=new LinkedList<FragmentActivity>();
}
if(activityListCapture==null){
activityListCapture=new LinkedList<FragmentActivity>();
}
}
public static ActivityManagement getInstance(){
if(instance==null){
instance=new ActivityManagement();
}
return instance;
}
public void addActivity(FragmentActivity acy) {
activityList.add(acy);
}
public void addActivityRegiser(FragmentActivity acy) {
activityListRegister.add(acy);
}
public void addActivityCapture(FragmentActivity acy) {
activityListCapture.add(acy);
}
/**
* 销毁所有
*/
public static void removeAll(){
FragmentActivity acy;
while (activityList.size() != 0) {
acy = activityList.poll();
if (acy != null && !acy.isFinishing()) {
acy.finish();
}
}
}
/**
* 销毁注册相关界面
*/
public static void removeRegisterAll(){
FragmentActivity acy;
while (activityListRegister.size() != 0) {
acy = activityListRegister.poll();
if (acy != null && !acy.isFinishing()) {
acy.finish();
}
}
}
/**
* 销毁注册相关界面
*/
public static void removeCaptureAll(){
FragmentActivity acy;
while (activityListCapture.size() != 0) {
acy = activityListCapture.poll();
if (acy != null && !acy.isFinishing()) {
acy.finish();
}
}
}
}
这里界面A和界面B,集成BaseActivity,所以我们在BaseActivity的onCreate中添加当前的引用到集合中去
第一步:BaseActivity中添加当前activity的引用
ActivityManagement.getInstance().addActivity(this)
第二步:在界面A中先清空,在添加
//移除做了判断,避免第一次创建的时候没有前一个空指针
ActivityManagement.removeCaptureAll()
ActivityManagement.getInstance().addActivityCapture(this)
第三步:在界面B添加,当前的应引用
ActivityManagement.getInstance().addActivityCapture(this)
最后就搞定了,想写Demo试试的话在 onCreate 和onDestory打印Log看看创建的次数即可
实现方式二: 界面A跳转界面B(此时销毁A),界面B在跳转界面A(此时销毁B),如此循环… 注:这些Activity都是在一个任务栈里面的
简单的实现为:
//只需要在界面跳转的时候,给Flag, findViewById(R.id.start_black).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent()
//设置这连个Flag就可以解决了
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.setClass(ActivityThird.this, ActivitySecond.class)
startActivity(intent)
}
})
如图: