cob*_*ero 7 android uncaughtexceptionhandler
我想在记录未处理的异常后关闭应用程序。在这里搜索后我做了以下事情:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
打电话后,defaultUEH.uncaughtException(thread, ex);我尝试打电话System.exit()( android.os.Process.killProcess(android.os.Process.myPid());甚至我发现一些帖子被告知要同时使用)。问题是我遇到黑屏,我必须使用手机任务管理器强制应用程序退出。我究竟做错了什么?
问候
最后我解决了这个问题,创建一个实现该Thread.UncaughtExceptionHandler接口的类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在BaseActivity我添加了以下代码:
//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);
}
Run Code Online (Sandbox Code Playgroud)
我知道它与我在问题中使用的代码相同,但不知何故它现在可以工作。当我有更多空闲时间时,我会深入研究以找到根本原因并将其发布
| 归档时间: |
|
| 查看次数: |
5794 次 |
| 最近记录: |