调用新的 activity 并销毁当前的

Call new activity and destroy current one

我有三个活动:A、B 和 C。

A 是对 B 的意图,B 是对 C 的意图,

当我在C中完成操作后,我想销毁 C然后回到A,而不是B。

我试过这个:

finish();
B b = new B();
b.finish();

在 C 中,不起作用;并且

finish();
B b = new B();
b.onDestroy();

在 C 中,它导致 NullPointerException

如何实现?

使用这个:

Intent i = new Intent(FromActivity.this,ToActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);

来自关于 Intent 的文档:

FLAG_ACTIVITY_NEW_TASK If set, this activity will become the start of a new task on this history stack

FLAG_ACTIVITY_CLEAR_TASK If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started.

完成您的操作后,您可以调用一个 intent 将您带到您想要的 Activity,如下所示:

Intent intent = new Intent(ActivityC.this, ActivityA.class);
startActivity(intent);
Intent i = new Intent(MainActivity.this,SecondActivity.class);
startActivity(i);
finish();

有几种方法可以做到这一点:

首先:将 android:noHistory 属性添加到清单中的 B activity,如下所示:

<activity android:name=".A"/>
<activity android:name=".B" android:noHistory="true"/> <!-- This attribute will prevent adding activity to activity stack-->
<activity android:name=".C"/>

第二个:刚开始新的就调用完成activity

// Put this code in your B activity
Intent intent = new Intent(this, C.class);
startActivity(intent);
finish() // This will finish current activity (activity B in your case) and activity stack will only contain A activity

第三:在你的 C activity intent

中放置标志 FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK
// Put this code in your B activity
Intent intent = new Intent(this, C.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // This will exclude current activity (activity B in your case) from activity stack
startActivity(intent);

Intent 调用 activity,然后调用 finish():

startActivity(new Intent(C.this, A.class));
finish();

finish() 将从返回堆栈中删除 activity 并且新的 activity 将作为 startActivity() 方法启动。