英文:
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
专注分享java语言的经验与见解,让所有开发者获益!
评论