Android 替换当前活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2116158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:35:53  来源:igfitidea点击:

Replace current activity

androidandroid-activity

提问by Richard Szalay

I need to replace the current activity with a new one. That is, I want to start a new activity and remove the current activity from the task stack.

我需要用新的活动替换当前的活动。也就是说,我想启动一个新活动并从任务堆栈中删除当前活动。

Based on the documentation, it seems the best way would be to start the activity using Activity.startActivityas per usual, and then call Activity.finishimmediately to close the current activity.

根据文档,似乎最好的方法是像往常一样使用Activity.startActivity启动活动,然后立即调用Activity.finish关闭当前活动。

Is this a valid usage of these APIs or should I be doing something else?

这是这些 API 的有效用法还是我应该做其他事情?

采纳答案by Tushar

Yes. It is fine to use api this way.

是的。这样使用api就好了。

回答by Jeremie D

The proper way to achieve this is using the following:

实现这一目标的正确方法是使用以下方法:

Intent intent = new Intent(this,MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
this.finish();

The code assumes you are in an activity, otherwise if you are using fragments use getActivity()

该代码假定您处于活动中,否则如果您使用片段,请使用getActivity()

This way, the activity is started, you properly set your hierarchy for your back button, and you also destroy the appropriate activity.

这样,活动就开始了,您为后退按钮正确设置了层次结构,并且您还销毁了相应的活动。

回答by user838411

try using FLAG_ACTIVITY_TASK_ON_HOME, FLAG_ACTIVITY_NEW_TASKin the intent flags

尝试在意图标志中使用FLAG_ACTIVITY_TASK_ON_HOME,FLAG_ACTIVITY_NEW_TASK

回答by Fangming Cheng

You can add android:launchMode="singleInstance" in your activity, then override onNewIntent method to update date

您可以在您的活动中添加 android:launchMode="singleInstance",然后覆盖 onNewIntent 方法以更新日期

Reference PlayerActivity in ExoPlayer Demo

在 ExoPlayer 演示中参考 PlayerActivity

回答by Andy Weinstein

You can use FLAG_ACTIVITY_CLEAR_TASK when you start the activity. I also defined the launchMode for my activity in the manifest as singleTask, but that was because I wanted that behavior for the new activity. I think you can get what you want with regard to clearing the previous activity regardless of what you use for launchMode with your new activity, as long as you pass startActivity the flag FLAG_ACTIVITY_CLEAR_TASK.

您可以在开始活动时使用 FLAG_ACTIVITY_CLEAR_TASK。我还在清单中将我的活动的launchMode 定义为singleTask,但那是因为我想要新活动的行为。我认为,只要您将 startActivity 标志 FLAG_ACTIVITY_CLEAR_TASK 传递给 startActivity,您就可以在清除以前的活动方面获得所需的内容,而不管您在新活动中使用什么来启动模式。