当前位置:操作系统 > 安卓/Android >>

Android 应用设置全局Exception处理事件的方法

通常情况下,如果Android应用出现未处理的异常,会出现下面类似的对话框,然后强制退出该应用:

 

\

如果你想改变这种缺省的行为,比如出现未处理异常时显示自定义对话框,或是重启该应用,可以使用下面步骤重定义Android全局异常处理事件。

1. 实现Thread.UncaughtExceptionHandler 接口

一般可以通过派生Application类并实现Thread.UncaughtExceptionHandler 方法:

[java] 
public class GNavigatorApplication extends Application 
  
implements   Thread.UncaughtExceptionHandler { 
  
... 
  

public class GNavigatorApplication extends Application
 
implements   Thread.UncaughtExceptionHandler {
 
...
 
}

2. 定义Thread.UncaughtExceptionHandler方法

比如重启某个Activity

[java] 
public void uncaughtException(Thread thread, Throwable ex) { 
  
Intent intent = new Intent(this, GNavigatorActivity.class); 
  
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP    | Intent.FLAG_ACTIVITY_NEW_TASK); 
  
startActivity(intent); 
  

public void uncaughtException(Thread thread, Throwable ex) {
 
Intent intent = new Intent(this, GNavigatorActivity.class);
 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP    | Intent.FLAG_ACTIVITY_NEW_TASK);
 
startActivity(intent);
 
}

3. 重置缺省的Exception处理函数,比如可以在OnCreate方法重设Exception处理方法。

[java]
@Override 
  
public void onCreate() { 
  
... 
  
Thread.setDefaultUncaughtExceptionHandler(this); 
  

@Override
 
public void onCreate() {
 
...
 
Thread.setDefaultUncaughtExceptionHandler(this);
 
}

这样在应用中出现未处理异常时,会自动重启应用,而不会出现Force Close对话框。

 作者:mapdigit
 

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,