简体   繁体   English

有没有办法重新启动应用程序,而不是让它在崩溃后重新启动上一个活动?

[英]Is there a way to restart the application instead of having it restart the last activity after a crash?

Since I store certain information that is necessary in my Application class, when a user encounters a crash, sometimes they encounter two crashes since the last activity needs information stored in the application class. 因为我在Application类中存储了某些必要的信息,所以当用户遇到崩溃时,有时他们会遇到两次崩溃,因为上一个活动需要在应用程序类中存储信息。

Activity A >> Activity B (needs info from Application class) >> Activity C 活动A >>活动B(需要来自应用程序类的信息)>>活动C

Crash occurs on C >> Application tries to open Activity B >> Crash occurs on B because it needs info from the Application class (this has been reset) C发生崩溃>>应用程序尝试打开活动B >> B发生崩溃,因为它需要Application类的信息(已重置)

I want to avoid this, so I was hoping that there is someway I can restart the whole application after a crash instead of the activity. 我想避免这种情况,所以我希望可以以某种方式在崩溃后重新启动整个应用程序,而不是重新启动活动。

This is one possible solution of many but I'll put it here as an option: 这是许多解决方案中的一种,但我将其作为一种选择:

You could use startActivityForResult() and when you handle the error in Activity C, finish() it with a result code that you recognize as a crash and handle things appropriately in the onActivityResult() of Activity B. 您可以使用startActivityForResult()并在活动C中处理错误时,使用可以识别为崩溃的结果代码finish()finish() ,并在活动B的onActivityResult()中适当地处理事情。

Getting a Result from an Activity 从活动中获取结果

The nicest solution is to handle the case in which you do not have the necessary information at any activity (in your case Activity B). 最好的解决方案是处理在任何活动(活动B)中都没有必要信息的情况。

You should check at the onCreate method whether you have the information or not, and act in consecuence: 您应该检查onCreate方法是否具有信息,并采取行动:

  • Finishing the activity to go back to your activity A 完成活动以返回到活动A
  • Launching another activity 发起另一项活动
  • Asking the user for feedback 要求用户提供反馈
  • Any other action you think fits best 您认为最合适的任何其他操作

There may be more than one reason explaining why you don't have that information (as other answers point out), so in my opinion the best option is to handle the case. 解释为什么您没有该信息的原因可能有多个(正如其他答案所指出的那样),所以我认为最好的选择是处理此案。

Untested theory, just spitballing. 未经检验的理论,只是吐口水。

Could you attach yourself as a default exception handler, and start calling finish() on the open activities? 您能否将自己附加为默认的异常处理程序,并开始在开放活动中调用finish() If you can finish all your activities, wouldn't that effectively shut down the app, and reopening it would be as if it were getting launched fresh? 如果您可以完成所有活动,那么就不能有效地关闭该应用程序,而重新打开该应用程序就像是在重新启动它一样吗?

You shouldn't keep any state in the Application object. 您不应该在Application对象中保留任何状态。 Keep it in the Bundle you receive in the onCreate(). 将其保存在您在onCreate()中收到的捆绑软件中。 Eventually use onSaveInstanceState / onRestoreInstanceState to save/restore state. 最终使用onSaveInstanceState / onRestoreInstanceState来保存/恢复状态。

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

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