本文主要讲如何在Application中对异常进行输出,并不让程序崩溃。关于Application的配置请查看http://blog.csdn.net/qq_32228265/article/details/58006956
直接贴代码
public class MyApplication extends Application {
private static Context context;// context
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
mainThreadId = android.os.Process.myTid();
// 设置异常的处理器
Thread.currentThread().setUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
}
public static Context getContext() {
return context;
}
private class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
// 异常处理器处理的代码 先输出日志 再自杀(闪退一下,程序不崩)
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// 死前的遗言
Log.i("tag", "出现异常了...");
ex.printStackTrace();// 异常打印到控制台
PrintStream err = null;
try {
err = new PrintStream(new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/error"
+ ".txt"));
ex.printStackTrace(err);// 把异常收集到文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (err != null) {
err.close();
}
}
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}