我可以在应用程序崩溃之前调用方法吗? [英] Can I call a method before my application go to crash
问题描述
我是android的新手,当我运行代码时,我总是看到Exception。
所以,有人可以告诉我在没有try-catch的应用程序崩溃之前我可以调用一个方法。
I'm a newbie in android and I always see Exception when I'm running my code. So, somebody can tell me Can I call a method before app go to crash anywhere without "try-catch".
推荐答案
这是处理未捕获异常的更好方法:
This would be better way to handle uncaught exception:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
appInitialization();
}
private void appInitialization() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
private UncaughtExceptionHandler defaultUEH;
// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
// TODO handle exception here
}
};
}
应用程序是需要维护全局应用程序状态的人的基类。因此,处理此类异常将是一个更好的地方。
Application is a Base class for those who need to maintain global application state. And hence here, it will be a better place to handle such exceptions.
编辑:
以上代码将处理未捕获的异常如果他们被抛入UI线程。
如果工作线程中发生异常,您可以通过以下方式处理它:
The above code will handle uncaught exceptions if they are thrown inside UI thread. If an exception has occurred in worker thread, you can handle it in following way:
private boolean isUIThread(){
return Looper.getMainLooper().getThread() == Thread.currentThread();
}
// Setup handler for uncaught exceptions.
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException (Thread thread, Throwable e)
{
handleUncaughtException (thread, e);
}
});
public void handleUncaughtException(Thread thread, Throwable e) {
e.printStackTrace(); // not all Android versions will print the stack trace automatically
if (isUIThread()) {
// exception occurred from UI thread
invokeSomeActivity();
} else { //handle non UI thread throw uncaught exception
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
invokeSomeActivity();
}
});
}
}
这篇关于我可以在应用程序崩溃之前调用方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!