真机调试安卓捕获应用的运行时异常并保存代码

在出错的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,里面显示的就是异常的内容
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值