我是靠谱客的博主 安静菠萝,最近开发中收集的这篇文章主要介绍Android 崩溃日志添加,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

我们的app难免会因为程序上的疏漏而停止运行,有时候提交出去的apk出现停止运行,为了更快的定位问题,我们会加上应用级的异常记录。这里代码记录下。日志主要包括时间和异常的类名字以及错误提示。

以下是定义的异常处理类 继承自Java提供的Thread.UncaughtExceptionHandler(说明:摘自网上, 当某一线程因未捕获的异常而即将终止时,Java 虚拟机将使用 Thread.getUncaughtExceptionHandler() 查询该线程以获得其 UncaughtExceptionHandler 的线程,并调用处理程序的 uncaughtException 方法,将线程和异常作为参数传递。如果某一线程没有明确设置其 UncaughtExceptionHandler,则将它的 ThreadGroup 对象作为其 UncaughtExceptionHandler。如果 ThreadGroup 对象对处理异常没有什么特殊要求,那么它可以将调用转发给默认的未捕获异常处理程序)

public class CrashCat implements Thread.UncaughtExceptionHandler {

    private static CrashCat crashCat;
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private static String DEVICE_INFO="";
    private File path;
    private File fileName;
    private FileOutputStream fileOutputStream;
    private BufferedOutputStream bufferedOutputStream;
    private static String FILE_NAME = "";
    private Intent intent;
    private PackageManager packageManager;
    private PackageInfo packageInfo;

    private CrashCat(Context context, String filePath, String fileName){
        init(context,filePath,fileName);
    }

    public static CrashCat getInstance(Context context, String filePath, String fileName){
        crashCat = new CrashCat(context,filePath,fileName);
        return  crashCat;
    }

    private void init(Context context, String filePath, String fileName){
        this.mContext = context;
        this.FILE_NAME = fileName;
        try {
            packageManager = mContext.getPackageManager();
            packageInfo = packageManager.getPackageInfo(mContext.getPackageName(),0);
            intent = packageManager.getLaunchIntentForPackage(mContext.getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } catch (Exception e) {
            writeLog(e.toString());
            intent = null;
        }
        path = new File(filePath);
        if (!path.exists()){
            path.mkdirs();
        }
        StringBuffer sb = new StringBuffer();
        sb.append("DeviceID="+ Build.ID+"n"); //手机型号
        sb.append("AndroidApi="+ Build.VERSION.SDK_INT+"n");//手机android版本号 数字 如23
        sb.append("AndroidVersion="+ Build.VERSION.RELEASE+"n");//android版本 如6.0
        sb.append("Brand="+ Build.BRAND+"n"); //手机商标
        sb.append("ManuFacture="+ Build.MANUFACTURER+"n");//生产商
        sb.append("Model="+ Build.MODEL+"n");//型号
        sb.append("PackageName="+mContext.getPackageName()+"n"); //应用包名
        sb.append("CurrentVersionName="+packageInfo.versionName+"n");//app版本号
        DEVICE_INFO = sb.toString();
        writeLog("Application Start");
    }

    public void start(){
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    private void writeLog(String log){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log = "----------"+simpleDateFormat.format(new Date(System.currentTimeMillis())).toString()+"----------"+"n"+log+"n";
        try {
            fileName = new File(path+FILE_NAME);
            if (fileName.exists() && fileName.length() > 10485760){
                fileName.delete();
            }
            fileOutputStream = new FileOutputStream(fileName,true);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            bufferedOutputStream.write(log.getBytes());
            bufferedOutputStream.flush();
            fileOutputStream.close();
            bufferedOutputStream.close();
        } catch (Exception e) {
            Log.e("IO Exception",e.toString());
        }
    }

    private void handlerException(String exception) {
        if (exception !=null){
            try{
                writeLog(DEVICE_INFO+exception.toString());
            }finally {
                try{
                    mContext.startActivity(intent);
                    Process.killProcess(Process.myPid());
                    System.exit(1);
                }catch (Exception e){
                    Log.e("App can not restart",e.toString());
                }
            }
        }
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        StringBuffer sb = new StringBuffer(e.toString()+"n");
        for (int i=0,size = stackTraceElements.length;i<size;i++){
            sb.append(stackTraceElements[i].toString()+"n");
        }
        Log.e("error",sb.toString());
        handlerException(sb.toString());
    }
}

接下来我们需要在application中使用这个CrashCat。

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        CrashCat.getInstance(getApplicationContext(), Environment.getExternalStorageDirectory().getPath()+ ConstValue.DIRECTORY_ROOT,ConstValue.FILE_LOG).start();
    }
}

然后在Manifest中注册这个application
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.wendy.demo.test">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name=".application.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.HomeActivity"
                  android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

最后

以上就是安静菠萝为你收集整理的Android 崩溃日志添加的全部内容,希望文章能够帮你解决Android 崩溃日志添加所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部