android app 捕获全局异常,保存成文件

CrashHandler :
package com.example.petrochina_oil;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作用:
 * 1.收集错误信息
 * 2.保存错误信息
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler sInstance = null;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Context mContext;
    // 保存手机信息和异常信息
    protected Map<String, String> mMessage = new HashMap<>();
    protected _Functions functions = new _Functions();
    String path = Environment.getExternalStorageDirectory().getPath() + "/mileCrash/";

    public static CrashHandler getInstance() {
        if (sInstance == null) {
            synchronized (CrashHandler.class) {
                sInstance = new CrashHandler();
            }
        }
        return sInstance;
    }

    private CrashHandler() {
    }

    /**
     * 初始化默认异常捕获
     *
     * @param context context
     */
    public void init(Context context) {
        mContext = context;
        // 获取默认异常处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 将此类设为默认异常处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
        List<String> log_files = functions.getFilesAllName(path);
        Log.d("init", "init");
        for (int i = 0; i < log_files.size(); i++) {
            postToServer(log_files.get(i));
        }
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (!handleException(e)) {
            // 未经过人为处理,则调用系统默认处理异常,弹出系统强制关闭的对话框
            if (mDefaultHandler != null) {
                mDefaultHandler.uncaughtException(t, e);
            }
        } else {
            // 已经人为处理,系统自己退出
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            Process.killProcess(Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 是否人为捕获异常
     *
     * @param e Throwable
     * @return true:已处理 false:未处理
     */
    private boolean handleException(Throwable e) {
        if (e == null) {// 异常是否为空
            return false;
        }
        Log.e("CrashHandler", "捕捉到异常");
        collectErrorMessages();
        saveErrorMessages(e);
        return false;
    }

    /**
     * 1.收集错误信息
     */
    private void collectErrorMessages() {
        PackageManager pm = mContext.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = TextUtils.isEmpty(pi.versionName) ? "null" : pi.versionName;
                String versionCode = "" + pi.versionCode;
                mMessage.put("versionName", versionName);
                mMessage.put("versionCode", versionCode);
            }
            // 通过反射拿到错误信息
            Field[] fields = Build.class.getFields();
            if (fields != null && fields.length > 0) {
                for (Field field : fields) {
                    field.setAccessible(true);
                    try {
                        mMessage.put(field.getName(), field.get(null).toString());
                        Log.e("collectErrorMessages", "收集异常信息");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存错误信息
     *
     * @param e Throwable
     */
    private void saveErrorMessages(Throwable e) {
        Log.e("saveErrorMessages", "保存异常信息");
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : mMessage.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        Throwable cause = e.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        Log.e("saveErrorMessages", "异常信息: " + result);
        saveToFile(result);
    }

    private void postToServer(final String file) {
        Log.d("crashPostToServer", "start");
        String strUrlPath = "http://119.3.56.22/index.php?m=Api&c=Alert&a=postAlert";
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        //formBody.add("mid",Config.get("mac"));//传递键值对参数
        formBody.add("code", "1001");//传递键值对参数
        String result = functions.getStrFromFile2("", file);
        Log.e("postToServer", "异常信息: " + result);
        formBody.add("description", result);//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url(strUrlPath)
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {//回调的方法执行在子线程。
                    if (response.code() == 200) {
                        functions.deleteSingleFile(file);
                    }
                }
            }
        });
    }

    private void saveToFile(String result) {
        String time = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss", Locale.CHINA).format(new Date());
        String fileName = time + ".log";
        functions.writeStrToFile2(result, fileName, path, false);
    }
}

调用:

CrashHandler.getInstance().init(this);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android应用中,可以通过全局捕获异常来避免应用闪退。可以通过以下步骤实现: 1. 创建一个自定义的Application类,并在其中重写`Thread.UncaughtExceptionHandler`接口的`uncaughtException`方法。 2. 在`uncaughtException`方法中处理全局异常,例如记录异常信息、上传日志或者进行其他处理操作。 3. 在Application的onCreate方法中,将自定义的UncaughtExceptionHandler设置为默认的异常处理器。 下面是一个示例代码: ```java public class MyApplication extends Application implements Thread.UncaughtExceptionHandler { @Override public void onCreate() { super.onCreate(); // 设置全局异常处理器 Thread.setDefaultUncaughtExceptionHandler(this); } @Override public void uncaughtException(Thread thread, Throwable ex) { // 处理全局异常,例如记录异常信息、上传日志等操作 Log.e("MyApplication", "Uncaught Exception: " + ex.getMessage()); // 重启应用或者执行其他操作 restartApp(); } private void restartApp() { // 重启应用,可以根据实际需求来实现 Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pendingIntent); // 退出应用 System.exit(0); } } ``` 记得在AndroidManifest.xml文件中将自定义的Application类配置为应用的默认Application类: ```xml <application android:name=".MyApplication" ...> ... </application> ``` 通过以上步骤,当应用发生未捕获异常时,会调用自定义的异常处理方法,你可以在其中进行相应的处理操作,例如记录异常信息、上传日志等。最后,你可以选择重启应用或者执行其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值