public class CrashHandler implements Thread.UncaughtExceptionHandler {

     public static final String TAG = "CrashHandler";

     // 系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler;
// CrashHandler实例
private static CrashHandler INSTANCE = new CrashHandler();
// 程序的Context对象
private Context mContext; //用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>(); //用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); /**
* 保证只有一个CrashHandler实例
*/
private CrashHandler() {
} /**
* 获取CrashHandler实例 ,单例模式
*/
public static CrashHandler getInstance() {
return INSTANCE;
} /**
* 初始化
* @param context
*/
public void init(Context context) {
mContext = context;
// 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
} /**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// ToastUtil.show(mContext, ex.getMessage());
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
// 退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
// KJActivityStack.create().AppExit(mContext);// 结束整个应用程序
}
} /**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
// 使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
//保存日志文件
String path = saveCrashInfo2File(ex);
return true;
} /**
* 保存错误信息到文件中
* @param ex
* @return 返回文件名称, 便于将文件传送到服务器
*/
private String saveCrashInfo2File(Throwable ex) {
infos = PhoneUtils.collectDeviceInfo(mContext);
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
FileOutputStream fos = null;
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = "/sdcard/aaaaaaaaaaaaaaaaaaaaacrash/";
// String path = mContext.getCacheDir() + "/crash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
Log.e(TAG, "an error occured while fos.close...", e);
}
}
return null;
}

APP全局异常捕获,并保存本地文件的更多相关文章

  1. Android全局异常捕获

    PS:本文摘抄自<Android高级进阶>,仅供学习使用 Java API提供了一个全局异常捕获处理器,Android引用在Java层捕获Crash依赖的就是Thread.Uncaught ...

  2. spring boot: GlobalDefaultExceptionHandler方法内的友好错误提示,全局异常捕获

    spring boot: GlobalDefaultExceptionHandler方法内的友好错误提示,全局异常捕获 当你的某个控制器内的某个方法报错,基本上回显示出java错误代码,非常不友好,这 ...

  3. .NET Core整合log4net以及全局异常捕获实现

    在使用log4net之前先安装log4net.这里操作很简单,通过nuget下载并安装log4net很方便.如下图. log4net配置 <?xml version="1.0" ...

  4. springboot 全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  5. 【快学springboot】5.全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  6. C#中的那些全局异常捕获

    1.WPF全局捕获异常     public partial class App : Application     {         public App()         {    // 在异 ...

  7. Asp.Net MVC3(三)-MvcApp实现全局异常捕获

    定义异常捕获类: [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMu ...

  8. .Net下的全局异常捕获问题

    全局异常捕获主要目标并不是为了将异常处理掉防止程序崩溃.因为当错误被你的全局异常捕获器抓到的时候,已经证实了你程序中存在BUG. 一般而言,我们的全局异常捕获主要作用就是接收到异常之后进行异常的反馈. ...

  9. (转)C#中的那些全局异常捕获

    C#中的那些全局异常捕获(原文链接:http://www.cnblogs.com/taomylife/p/4528179.html)   1.WPF全局捕获异常       public partia ...

随机推荐

  1. windows下curl报错:curl : (1) Protocol https not supported or disabled in libcurl

    如果命令语句中有单引号,改为英文双引号试一下

  2. 通过终端安装程序sudo apt-get install ***时出错:

    E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)  E: Unable to ...

  3. [Functional Programming] Draw Items from One JavaScript Array to Another using a Pair ADT

    We want to be able to pick nine random cards from an array of twelve cards, but can run into problem ...

  4. 用C#封装的ServiceStack.redis操作类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. [转]2年SQL Server DBA调优方面总结

      2年SQL Server DBA调优方面总结 当2年dba 我觉得,有些东西需要和大家分享探讨,先书单. 书单 1.<深入解析SQL Server 2008 系列> 这个就是mssql ...

  6. Python学习笔记(四)多进程的使用

    python中多进程与Linux 下的C基本相同.   fork的基本使用   先看最简单的例子: # coding: utf-8 import os def my_fork(): pid = os. ...

  7. python基础语法(一)

    Python的特点 1. 简单 Python是一种代表简单思想的语言. 2. 易学 Python有极其简单的语法. 3. 免费.开源 Python是FLOSS(自由/开放源码软件)之一. 4. 高层语 ...

  8. Vue webpack配置文件

    一.代码地址 github:https://github.com/MengFangui/VueWebpackConfig 二.配置说明 1.命令 (1)npm i 安装依赖包 (2)num run d ...

  9. springboot+thymeleaf打war包在外部tomcat运行

    工程目录 pom文件注意点 <packaging>war</packaging> <dependency> <groupId>org.springfra ...

  10. jQuery读取json文件

    转 http://www.jb51.net/article/36678.htm 1.userInfo.html <!DOCTYPE html PUBLIC "-//W3C//DTD X ...