我想全局捕获所有可能的安卓异常,以便应用程序不能关闭。

huangapple 未分类评论49阅读模式
英文:

I want to catch all possible android exception globally so application can't close

问题

我想在一个类中捕获所有可用的异常,以便应用程序不会意外关闭。
我为此编写了一些代码,但代码无效。

MyApplication.java 类




import android.app.Application;

public class MyApplication extends Application {

    private static MyApplication mInstance;
    private Thread.UncaughtExceptionHandler defaultUEH;
    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
            new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread thread, Throwable ex) {

                    // 在此处将异常记录到数据库中
//                    Log.d("MyApp", "Uncaught exception.");
                    // 进行你想要的操作。

                    // 如果问题严重并且需要由操作系统处理,可以将异常重新抛给操作系统。在那时取消下一行的注释。
                    //defaultUEH.uncaughtException(thread, ex);
                }
            };

    public MyApplication() {
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }



}

那么如何调用 _unCaughtExceptionHandler 对象呢?

英文:

I want to catch all available exception cause in one class so the app isn't unexpectedly close.
I write some code for it but it doesn't work

MyApplication.java class




import android.app.Application;

public class MyApplication extends Application {

    private static MyApplication mInstance;
    private Thread.UncaughtExceptionHandler defaultUEH;
    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
            new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread thread, Throwable ex) {

                    // here I do logging of exception to a db
//                    Log.d("MyApp", "Uncaught exception.");
                    // Do what you want.

                    // re-throw exception to O.S. if that is serious and need to be handled by o.s. Uncomment the next line at that time.
                    //defaultUEH.uncaughtException(thread, ex);
                }
            };

    public MyApplication() {
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

 


}

So how i call _unCaughtExceptionHandler object

huangapple
  • 本文由 发表于 2020年6月29日 14:01:13
  • 转载请务必保留本文链接:https://java.coder-hub.com/62632125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定