我想知道是否可以清除旧 Activity 中的所有 Activity 。我想使用 enventBus 来执行此操作。
Activity 堆栈示例:
startActivity(A) then startActivity(B) then startActivity(C) then startActivity(D)...
Activity B 在事件总线上注册了 onEvent(ClearStackFromHere())。
并且从 Activity D 我也想用 eventBus 发布事件帖子(新的 ClearStackFromHere)。
那么,是否可以从 B 清除 Activity 堆栈?
我应该在 ClearStackFromHere() 中写些什么。
谢谢,
最佳答案
我在我的一个项目中实现了类似的解决方案。
我需要的是一种方法,只在后台堆栈中保留最近的 3 个 Activity ,并清除它们之前的其他 Activity 。这仅适用于我的应用程序中的某个导航流程,在该流程中可以将无限数量的 Activity 添加到后台堆栈。
例如A 打开 B - B 打开 C,然后 C 可以打开 A 或 B 的另一个实例......等等。
我应该注意到,此解决方案使用 EventBus 2.4.0,并且可能有更好的方法使用 3.0+ 来实现它。
首先,我定义了一个名为 ActivityTracker
的助手。它跟踪当前 Activity 的 Activity 以及每个 Activity 的标识符。它还具有可以调用的方法来完成返回堆栈中的所有 Activity ,除了最近的 n 个金额。
public class ActivityTracker {
private static ArrayList<String> activityStack = new ArrayList<>();
//Notify the Tracker of a new Activity to track
public static void activityActive(String uuid){
addToBackStack(uuid);
}
//Notify the tracker of an Activity that should no longer be tracked
public static void finishing(String uuid){
removeFromBackStack(uuid);
}
//Call this to clear entire back stack
public static void killAllBackStackActivities(){
killPreviousActivities(0);
}
//Call this to clear back stack while keeping most recent X amount
private static void killPreviousActivities(int keepAmount){
if(activityStack.size() <= keepAmount) {
return;
}
//Copy to not manipulate while looping.
String[] tempList = activityStack.toArray(new String[activityStack.size()]);
int counter = activityStack.size();
for(String id : tempList){
if(counter == keepAmount){
return;
}
counter--;
//Send notification to kill specific activity
EventBus.getDefault().post(new ActivityShouldDieEvent(id));
}
}
private static void addToBackStack(String uuid){
if(!activityStack.contains(uuid)){
activityStack.add(uuid);
killPreviousActivities(3); //Always kill all activities except most recent 3.
}
}
private static void removeFromBackStack(String uuid){
if(activityStack.contains(uuid))
activityStack.remove(uuid);
}
}
然后,我定义了 AppCompatActivity
的子类,称为 BackStackTrackActivity
。应用程序中的所有相关 Activity 都扩展了此类。子类如下所示:
public class BackStackTrackActivity extends AppCompatActivity {
//Random ID for activity to be identified by
protected String uuid = UUID.randomUUID().toString();
//Receive notification that activity should finish
public void onEvent(ActivityShouldDieEvent ev){
if(ev.getUuid().equals(this.uuid)){
finish();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//Unregister from EventBus
EventBus.getDefault().unregister(this);
//Tell tracker to stop tracking
ActivityTracker.finishing(uuid);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Register for events
EventBus.getDefault().register(this);
//Tell tracker to track activity
ActivityTracker.activityActive(uuid);
}
}
通过一些工作,我认为您将能够将此解决方案调整为满足您需求的东西。
希望对您有所帮助。
关于java - 使用 eventBus 从特定 Activity 中清除堆栈 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36871318/