Android异常处理最佳做法? [英] Android exception handling best practice?

查看:125
本文介绍了Android异常处理最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的应用程序崩溃,它会挂起几秒钟,之后我被Android通知应用程序崩溃并需要关闭。所以我正在考虑用我的应用程序捕获所有例外:

If my app crashes, it hangs for a couple of seconds before I'm told by Android that the app crashed and needs to close. So I was thinking of catching all exceptions in my app with a general:

try {
    // ... 
} catch(Exception e) { 
    // ...
} 

并创建一个新的活动,解释应用程序立即崩溃(并且还让用户有机会发送带有错误详细信息的邮件),而不是这样延迟感谢Android。有没有更好的方法来完成这个或者这是不鼓励的?

And make a new Activity that explains that the application crashed instantly (and also giving users an opportunity to send a mail with the error details), instead of having that delay thanks to Android. Are there better methods of accomplishing this or is this discouraged?

更新:我正在使用带有ART功能的Nexus 5,我没有注意到我曾经遇到的应用程序崩溃的延迟(我原本在说的挂起)。我认为,由于所有的东西都是本地代码,所以崩溃事件会立即发生,同时得到所有的崩溃信息。也许Nexus 5只是快速:)不管这可能不是担心在未来的Android版本(鉴于ART将是Android L中的默认运行时)。

Update: I am using a Nexus 5 with ART enabled and I am not noticing the delay I used to experience with apps crashing (the "hanging" I was talking about originally). I think since everything is native code now, the crash happens instantly along with getting all the crash information. Perhaps the Nexus 5 is just quick :) regardless, this may not be a worry in future releases of Android (given that ART is going to be the default runtime in Android L).

推荐答案

这里,检查链接以供参考

在这里你创建一个类说 ExceptionHandler 实现java.lang.Thread.UncaughtExceptionHandler ..

In here you create a class say ExceptionHandler that implements java.lang.Thread.UncaughtExceptionHandler..

在这个课堂里,你会做你的救命物品创建堆栈跟踪并准备上传错误报告等....

Inside this class you will do your life saving stuff like creating stacktrace and gettin ready to upload error report etc....

现在是重要的部分,即如何捕获该异常。
虽然很简单在您覆盖 onCreate 方法的超级方法调用之后,在每个Activity中复制以下代码行。

Now comes the important part i.e. How to catch that exception. Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

您的活动可能看起来像这样...

Your Activity may look something like this…

public class ForceClose extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

        setContentView(R.layout.main);
    }
}

希望这有帮助...

这篇关于Android异常处理最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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