在出错的Activity的onCreate()加入如下代码:
// 捕获应用的运行时异常
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
// 给主线程设置一个处理运行时异常的handler
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
StringBuilder sb = new StringBuilder();
sb.append("Version code is ");
sb.append(Build.VERSION.SDK_INT + "\n");
// 设备的Android版本号
sb.append("Model is ");
sb.append(Build.MODEL + "\n");
// 设备型号
sb.append(sw.toString());
try {
saveToSDCard("myException.txt", sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
});
同时加入如下方法:
public void saveToSDCard(String fileName, String content)
throws IOException {
// 考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录
File file = new File(Environment.getExternalStorageDirectory(),
fileName);
if (!file.isDirectory()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
在Android的manifest.xml文档中加入下面的声名:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
就可以在手机的SD卡根目录查找myException.txt,里面显示的就是异常的内容
// 捕获应用的运行时异常
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
// 给主线程设置一个处理运行时异常的handler
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
StringBuilder sb = new StringBuilder();
sb.append("Version code is ");
sb.append(Build.VERSION.SDK_INT + "\n");
// 设备的Android版本号
sb.append("Model is ");
sb.append(Build.MODEL + "\n");
// 设备型号
sb.append(sw.toString());
try {
saveToSDCard("myException.txt", sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
});
同时加入如下方法:
public void saveToSDCard(String fileName, String content)
throws IOException {
// 考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录
File file = new File(Environment.getExternalStorageDirectory(),
fileName);
if (!file.isDirectory()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
在Android的manifest.xml文档中加入下面的声名:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
就可以在手机的SD卡根目录查找myException.txt,里面显示的就是异常的内容