Android 程序崩溃自动生成Crash文件

1.添加依赖

implementation 'com.google.code.gson:gson:2.8.5'

2.添加权限




    

    
        
            
                

                
            
        
    


3.初始化

package com.scarf.topnews;

import android.app.Application;

import com.scarf.topnews.utils.CrashHandler;

/**
 * Created on 2018/11/15 13:49
 *
 * @author Scarf Gong
 */
public class MyApp extends Application{
    @Override
    public void onCreate() {
        super.onCreate();

        CrashHandler.init(getApplicationContext());

    }
}

4.CrashHandler

package com.scarf.topnews.utils;

import android.content.Context;

/**
 * Created on 2018/11/15 14:52
 *
 * @author Scarf Gong
 */
public class CrashHandler {
    private CrashHandler() {}

    public static void init(Context context) {
        new MyExceptionHandler(context).init();
    }
}

5.MyExceptionHandler

package com.scarf.topnews.utils;

import android.content.Context;
import android.os.Environment;

import com.scarf.topnews.bean.LogBean;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created on 2018/11/15 13:57
 *
 * @author Scarf Gong
 */
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = MyExceptionHandler.class.getSimpleName();
    private static final String BASE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "enterprise" + File.separator + "log";

    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    MyExceptionHandler(Context context) {
        this.mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void init() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Thread.setDefaultUncaughtExceptionHandler(null);
        saveCrashToFile(e);
        mDefaultHandler.uncaughtException(t, e);
    }

    private void saveCrashToFile(Throwable throwable) {
        // get the crash report
        StackTraceElement[] stackTraceElements = throwable.getCause().getStackTrace();
        List stackTraceElementList = new ArrayList<>(Arrays.asList(stackTraceElements));
        String detailMessage = throwable.getLocalizedMessage();

        // get device info
        String versionName = DeviceUtil.getVersionName(mContext);
        String manufacturer = DeviceUtil.getManufacturer();

        // get time
        String time = formatter.format(new Date());

        LogBean logBean = new LogBean();
        logBean.time = time;
        logBean.versionName = versionName;
        logBean.manufacturer = manufacturer;
        logBean.detailMessage = detailMessage;
        logBean.stackTraceElements = stackTraceElementList;
        String builder = GsonUtil.toStr(logBean);

        // save file
        InputStream inputStream = new ByteArrayInputStream(builder.getBytes());
        FileUtil.saveInputStreamToFile(inputStream, BASE_DIR, time + ".txt");
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.工具类

6.1、DeviceUtil

package com.scarf.topnews.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

/**
 * Created on 2018/9/14 11:28
 *
 * @author Scarf Gong
 */
public class DeviceUtil {

    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pInfo = null;

        try {
            PackageManager pManager = context.getPackageManager();
            pInfo = pManager.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pInfo;
    }

    public static boolean isVt320Device() {
        return Build.MANUFACTURER.contains("SEUIC");
    }

    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }
}

6.2、GsonUtil

package com.scarf.topnews.utils;

import com.google.gson.Gson;

/**
 * @author David Qin
 * created on 2018/11/15
 */
public class GsonUtil {
    private static Gson sGson = new Gson();

    public static String toStr(Object o) {
        return sGson.toJson(o);
    }

    public static  T toObj(String json, Class tClass) {
        return sGson.fromJson(json, tClass);
    }
}

6.3、FileUtil

package com.scarf.topnews.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created on 2018/11/15 13:52
 *
 * @author Scarf Gong
 */
public class FileUtil {
    private FileUtil() {
    }

    public static boolean isFileExists(String path, String name) {
        File file = new File(path, name);
        return file.exists();
    }

    public static void saveInputStreamToFile(InputStream inputStream, String path, String name) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(path, name);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fileOutputStream = null;
        try {
            file.createNewFile();
            fileOutputStream = new FileOutputStream(file);
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String str = sb.toString();
            fileOutputStream.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static FileInputStream getFileInputStreamFromPath(String path, String name) {
        File file = new File(path, name);
        if (file.exists()) {
            try {
                return new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}

7.LogBean

package com.scarf.topnews.bean;

import java.util.List;

/**
 * Created on 2018/11/15 14:48
 *
 * @author Scarf Gong
 */
public class LogBean {
    public String time;
    public String versionName;
    public String manufacturer;
    public String detailMessage;
    public List stackTraceElements;
}

8.模拟崩溃

package com.scarf.topnews;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView.setText("hello");
    }
}

**tips:**如果没有文件,因为里不是用动态申请权限。所以需要手动去打开此项目的权限。

你可能感兴趣的:(Android微技巧)