如果另一个 Activity 崩溃,Android 将返回到前一个 Activity
如果另一个 Activity
导致抛出未处理的异常,是否有办法要求 Android 返回到我的应用程序中的上一个 Activity
?
Is there a way to ask Android to return to a previous Activity
within my application in the event that another Activity
causes an unhandled exception to be thrown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试使用
Thread.setDefaultUncaughtExceptionHandler
当任何线程由于未处理的异常而死亡时接收通知。但我不确定 Dalvik 是否实现了该机制。您可能无法从 UncaughtExceptionHandler 启动另一个活动,因为文档没有提及线程/进程复活。更新
好的。我对其进行了测试,现在我确信如果您的应用程序在 UI 线程中引发异常,您将无法使用上述技术返回到先前的 Activity。发生这种情况是因为该异常会导致应用程序 主循环程序 退出,因此您的应用程序将无法处理任何进一步的 UI 消息。
我发现实现您想要的效果的唯一可能方法是以下脏黑客:
并在 AndroidManifest.xml 中注册 MyApplication:
showPreviousActivity()
方法的实现取决于您。一种可能的解决方案是跟踪某个 ActivityTracker 类中当前的 Activity 实例,并从showPreviousActivity
代码中调用当前活动的finish()
方法。You can try to use
Thread.setDefaultUncaughtExceptionHandler
to receive notification when any thread has died due to an unhandled exception. But I'm not sure about Dalvik implementation of that mechanism. It could be possible you would not be able to start another activity from theUncaughtExceptionHandler
as the documentation says nothing about thread/process resurrection.Update
Ok. I tested it and now I'm sure you will NOT be able to return to a previous Activity using the above technique if your application thrown an exception in the UI thread. This happens because that exception would cause application main looper to exit and thus your application would not be able to process any further UI messages.
The only possible way I've found to achieve what you want is the following dirty-hack:
And register MyApplication in your AndroidManifest.xml:
The implementation of the
showPreviousActivity()
method is up to you. One of the possible solution would be to keep track of the currently Activity instance in some ActivityTracker class and to call current activityfinish()
method from theshowPreviousActivity
code.使用
try-catch
块捕获异常并在那里使用startActivity
。您不能在没有赶上另一项活动的情况下去参加它。Use a
try-catch
block to catch the exception andstartActivity
there. You can not go to another activity without catching it.