Android中如果应用出现异常,程序不做处理的话,通常会弹出“强行关闭”对话框,如下:
为了给用户更好的体验不需要抛出该对话框,需要对异常进行处理,写了一个例子,处理方式是捕获全局异常。工程目录如下:
其中CustomApplication是自定义的Application,用来注册全局异常,CustomException用来对异常进行处理,MainActivity中模拟了一个异常。首先看一下CustomApplication代码:
public class CustomApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CustomException customException = CustomException.getInstance();
customException.init(getApplicationContext());
}
}
继承了Application,同时将CustomException注册到CustomApplication中。
CustomException实现了UncaughtExceptionHandler ,主要代码如下:
public class CustomException implements UncaughtExceptionHandler {
//获取application 对象;
private Context mContext;
private Thread.UncaughtExceptionHandler defaultExceptionHandler;
//单例声明CustomException;
private static CustomException customException;
private CustomException(){
}
public static CustomException getInstance(){
if(customException == null){
customException = new CustomException();
}
return customException;
}
@Override
public void uncaughtException(Thread thread, Throwable exception) {
// TODO Auto-generated method stub
if(defaultExceptionHandler != null){
Log.e("tag", "exception >>>>>>>"+exception.getLocalizedMessage());
//将异常抛出,则应用会弹出异常对话框.这里先注释掉
// defaultExceptionHandler.uncaughtException(thread, exception);
}
}
public void init(Context context) {
mContext = context;
defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);}
}
其中
public void uncaughtException(Thread thread, Throwable exception) {
// TODO Auto-generated method stub
if(defaultExceptionHandler != null){
Log.e("tag", "exception >>>>>>>"+exception.getLocalizedMessage());
//将异常抛出,则应用会弹出异常对话框.这里先注释掉
// defaultExceptionHandler.uncaughtException(thread, exception);
}
}
对异常作出处理。然后在Mainfest中添加CustomApplication,如下:
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:name="CustomApplication">
最后,在MainActivity中抛出异常,代码如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//模拟异常
throw new RuntimeException("my exception error");
}
程序运行日志结果如下:
源代码见:http://bigcateasymorse.googlecode.com/svn/trunk/android_exception_demo/