Android 全局异常捕捉,并发送到服务器 Thread.UncaughtExceptionHandler

/**

*参考代码

*/

public class ApplicationExceptionhandler implements Thread.UncaughtExceptionHandler {
 
    private Context context;
    private Thread.UncaughtExceptionHandler defalutHandler;
 
    /**
     * 异常处理初始化
     *
     * @param context
     */
    public void init(Context context) {
        this.context = context;
        // 获取系统默认的UncaughtException处理器
        defalutHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        // 自定义错误处理
        boolean res = handleException(ex);
        if (!res && defalutHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            defalutHandler.uncaughtException(thread, ex);

        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e("UnCaughtException", "error : ", e);
            }
            ex.printStackTrace();
            // 退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        //输出带行数的具体错误信息
        String  errorStr= Log.getStackTraceString(ex);//直接将该信息直接写入文件即可
   
        Log.e("7878",errorStr);

        return true;
    }




    public static List<String> getStrList(String inputString, int length) {
        int size=inputString.length()/length;
        int a=inputString.length()-length*size;
        if(inputString.length()-length*size>0){
            size+=1;
        }
        List<String> list = new ArrayList<String>();
        for (int index = 0; index < size; index++) {
            if(index==size-1){
                String childStr = inputString.substring( index * length,
                        index * length+a);
                list.add(childStr);
            }else{
                String childStr = inputString.substring( index * length,
                        (index + 1) * length);
                list.add(childStr);
            }
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/hadkfhkdh/article/details/85317249