简体   繁体   English

按下手机后如何关闭Android应用程序

[英]How do you close an android app after pressing back on the phone

On my app I would like to close the app when reaching the mainActivity.在我的应用程序中,我想在到达 mainActivity 时关闭该应用程序。 At the moment I have noHistory added to all activities in the manifest because I am overriding the navigation based on how I would like the app to flow.目前,我没有向清单中的所有活动添加 noHistory,因为我正在根据我希望应用程序的运行方式覆盖导航。

What code would I put into the onBackPressed function to close the app?我会在 onBackPressed 函数中放入什么代码来关闭应用程序?

The issue I have is that I do not want to use noHistory because when moving between apps or minimizing the app, the app will load from the splash screen again when you open it which is not helpful for navigation我的问题是我不想使用 noHistory 因为在应用程序之间移动或最小化应用程序时,应用程序将在您打开它时再次从启动画面加载,这对导航没有帮助

NOTE : I have a splash screen implemented as well.注意:我也实现了启动画面。

The root activity can use startActivityForResult with a certain request code constant.根活动可以使用带有特定请求代码常量的startActivityForResult The next activity can call setResult(RESULT_OK, Intent()) in its onCreate (not sure if this step is necessary).下一个活动可以在其onCreate调用setResult(RESULT_OK, Intent()) (不确定这一步是否必要)。 Then back in the first activity, override onActivityResult and call finish() if the request code matches the one you used in the startActivityForResult call.然后回到第一个活动,如果请求代码与您在startActivityForResult调用中使用的代码匹配,则覆盖onActivityResult并调用finish()

No need to override onBackPressed .无需覆盖onBackPressed

Alternatively, the root activity can simply call finish() immediately after startActivity() .或者,根活动可以简单地在startActivity()之后立即调用finish() startActivity() Then it won't be in the back stack at all.然后它根本不会在后堆栈中。

You can just call finish() in onBackPressed() .您可以在onBackPressed()调用finish() onBackPressed() It should be enough.应该够了。 Alternatively you can call System.exit(0) .或者,您可以调用System.exit(0)

More here: Difference between finish() and System.exit(0)更多信息: finish() 和 System.exit(0) 之间的区别

The answer is kind of combination of all but much simpler but a little cumbersome.答案是所有的组合,但要简单得多,但有点麻烦。

What i actually needed to do was add finish() wherever i had a startActivity in each of the activities and this could have been multiple depending on the actions in the page.我实际上需要做的是在每个活动中我有startActivity任何地方添加finish() ,这可能是多个,具体取决于页面中的操作。

This ultimately allows navigation back tot he main page and when closed, "minimizes" the app in the app drawer of the phone.这最终允许导航回到主页面,并在关闭时“最小化”手机应用程序抽屉中的应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM