Android的回归到previous活动,如果另一个活动撞车 [英] Android return to a previous Activity if another Activity crashes

查看:106
本文介绍了Android的回归到previous活动,如果另一个活动撞车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法问的Andr​​oid返回到previous 活动在我的事件的应用程序,另一个活动导致未处理的异常被抛出?

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?

推荐答案

您可以尝试使用<一个href="http://developer.android.com/reference/java/lang/Thread.html#setUncaughtExceptionHandler%28java.lang.Thread.UncaughtExceptionHandler%29"相对=nofollow> Thread.setDefaultUncaughtExceptionHandler 收到通知时,任何线程由于未处理的异常死亡。但我不知道的Dalvik实施该机制。这可能是可能的,你将无法启动从另一个活动的的UncaughtExceptionHandler 作为文档只字未提线程/进程的复活。

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 the UncaughtExceptionHandler as the documentation says nothing about thread/process resurrection.

更新

确定。我测试了它,现在我敢肯定,你会不会可以重新使用上述技术中的previous活动,如果您的应用程序扔在UI线程例外。这是因为该异常会导致应用程序主尺蠖退出,因此您的应用程序将无法处理任何进一步的UI消息。

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:

public class MyApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    while (true) {
      try {
        Log.i("MyLooper", "Starting my looper");
        Looper.loop();
      } catch (Exception e) {
        Log.e("MyLooper", "Caught the exception in UI thread, e:", e);
        showPreviousActivity();
      }
    }
  }

  private void showPreviousActivity() {
    // your implementation of showing the previous activity
  }   
}

而在你的Andr​​oidManifest.xml注册MyApplication的:

And register MyApplication in your AndroidManifest.xml:

<application android:name=".MyApplication">
…

显示previousActivity()方法的实现是由你。其中一个可能的解决方案将是跟踪当前活动实例在一些ActivityTracker类,并调用当前活动完成() show方法previousActivity code。

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 activity finish() method from the showPreviousActivity code.

这篇关于Android的回归到previous活动,如果另一个活动撞车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆