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

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

问题描述

如果我的应用程序崩溃,挂起了几秒钟之前,我用的Andr​​oid告知,该应用程序崩溃,需要关闭。所以我想抓住我的应用程序的所有异常与一般的:

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?

更新:我正在使用的Nexus 5与ART启用,我没有注意到我使用的应用程序崩溃体验的延迟(以下简称挂原本我是在谈论)。我想既然一切都是原生code现在,坠机发生的瞬​​间以及让所有的崩溃信息。或许Nexus的5只是快:)不管,这可能不是在Android的未来版本的担心(因为艺术是要在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....

现在到了最重要的部分即如何捕获了异常。 虽然这是非常简单的。复制code以下行的每一项活动都只是超级方法中调用您的重写的onCreate 方法。

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);
    }
}

希望这有助于...

Hope this helps...

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

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