问题
I want to close the app after logging an unhandled exception. After searching here i made the following:
public class MyApplication extends Application {
//uncaught exceptions
private Thread.UncaughtExceptionHandler defaultUEH;
// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
//logging code
//..........
//call the default exception handler
defaultUEH.uncaughtException(thread, ex);
}
};
public MyApplication() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
}
After calling defaultUEH.uncaughtException(thread, ex);
i tried to call System.exit()
and also android.os.Process.killProcess(android.os.Process.myPid());
(even i found some posts where is told to use both). The problem is that im getting a black screen and i have to force the app exit with the phone task manager. What am i doing wrong?
Regards
回答1:
At last i resolved this making a class implementing the Thread.UncaughtExceptionHandler
interface:
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private BaseActivity activity;
private Thread.UncaughtExceptionHandler defaultUEH;
public MyUncaughtExceptionHandler(BaseActivity activity) {
this.activity = activity;
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void setActivity(BaseActivity activity) {
this.activity = activity;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//LOGGING CODE
//........
defaultUEH.uncaughtException(thread, ex);
}
}
In the BaseActivity
i added the following code:
//exception handling
private static MyUncaughtExceptionHandler _unCaughtExceptionHandler;
@Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
if(_unCaughtExceptionHandler == null)
_unCaughtExceptionHandler = new MyUncaughtExceptionHandler(this);
else
_unCaughtExceptionHandler.setActivity(this);
if(Thread.getDefaultUncaughtExceptionHandler() != _unCaughtExceptionHandler)
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
I know its the same code i have in the question, but somehow its working now. When i have more free time i will look this deeply to find the root cause and post it
来源:https://stackoverflow.com/questions/38896483/android-uncaughtexceptionhandler-to-finish-app