1.直接贴代码
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;import com.nuotu.atmBookClient.App;import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;/*** 全局捕获导常,保存到本地错误日志。日志* 路径位于sdcard/错误日志Log/myErrorLog下。*/
public class MyCrashHandler implements UncaughtExceptionHandler {private static MyCrashHandler instance;//报错具体信息内容,具体到是哪一行报错String result;public static MyCrashHandler getInstance() {if (instance == null) {instance = new MyCrashHandler();}return instance;}private Thread.UncaughtExceptionHandler mDefaultHandler;public void init(Context ctx) {// 获取默认异常处理器mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 将当前类设为默认异常处理器Thread.setDefaultUncaughtExceptionHandler(this);}/*** 核心方法,当程序crash 会回调此方法, Throwable中存放这错误日志*///如果程序出现报错,闪退,有错误信息,都会回调到这个方法@Overridepublic void uncaughtException(Thread arg0, Throwable arg1) {Log.d("111333","打印报错信息="+arg1.getMessage());//这个if语句进行报错信息捕获,并用result接收if (handleException(arg1)) {// 已经处理,APP重启,方法放在最下面// restartApp();} else {// 如果不处理,则调用系统默认处理异常,弹出系统强制关闭的对话框if (mDefaultHandler != null) {mDefaultHandler.uncaughtException(arg0, arg1);}}String logPath;if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {logPath = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+ File.separator+ "错误日志Log";//我们可以根据这个路径去手机内存中查找这个文件Log.d("1113332","打印报错信息文件的存放路径="+logPath);File file = new File(logPath);if (!file.exists()) {file.mkdirs();}try {FileWriter fw = new FileWriter(logPath + File.separator+ "myErrorlog.log", true);// 错误信息// 这里还可以加上当前的系统版本,机型型号 等等信息StackTraceElement[] stackTrace = arg1.getStackTrace();//这里用write方法进行数据写入到文件中fw.write(getNowTime());//这里暂时注释,这个for循环的报错信息不够具体
// for (int i = 0; i < stackTrace.length; i++) {
// fw.write("file:" + stackTrace[i].getFileName() + " class:"
// + stackTrace[i].getClassName() + " method:"
// + stackTrace[i].getMethodName() + " line:"
// + stackTrace[i].getLineNumber() + "\n");
// }fw.write("\n========================这里存放最重要的错误信息提示,具体到哪一行报错(开始)===========================\n");fw.write(result);fw.write("\n========================这里存放最重要的错误信息提示,具体到哪一行报错(结束)===========================\n");fw.close();// 上传错误信息到服务器// uploadToServer();} catch (IOException e) {Log.e("crash handler", "load file failed...", e.getCause());}}arg1.printStackTrace();//这行代码是杀死进程,暂时注释// android.os.Process.killProcess(android.os.Process.myPid());}private boolean handleException(Throwable e) {if (e == null) {return false;}Writer writer = new StringWriter();PrintWriter pw = new PrintWriter(writer);e.printStackTrace(pw);pw.close();//这里捕获报错日志,用result接收result = writer.toString();// 打印出错误日志Log.d("111333", "打印出错误日志================================(开始)\n"+result+"打印出错误日志================================(结束)\n");return true;}/*** 1s后让APP重启*/private void restartApp() {Intent intent = App.getContext().getPackageManager().getLaunchIntentForPackage(App.getContext().getPackageName());PendingIntent restartIntent = PendingIntent.getActivity(App.getContext(), 0, intent, 0);AlarmManager mgr = (AlarmManager) App.getContext().getSystemService(Context.ALARM_SERVICE);// 1秒钟后重启应用mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);System.exit(0);}/*** 获取当前时间** @return 当前时间*/private static String getNowTime() {SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date curDate = new Date(System.currentTimeMillis());//获取当前时间return formatter.format(curDate);}}
2.在Application中进行初始化
import android.app.Application;public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//打开错误日志,保存到sd卡MyCrashHandler myCrashHandler = MyCrashHandler.getInstance();myCrashHandler.init(getApplicationContext());TextView t=null;//这里写一个空对象,调用他的方法,进行报错t.setText("");}
}
3.修改mainfests,添加权限,修改application节点。需要配置全局启动类,不然不会启动MyApplication 类。还有需要注意,如果是安卓6.0以上的系统需要动态申请权限(读写文件权限)。
就是图片中的权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.yu.myapplication"><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><applicationandroid:name=".MyApplication"android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme"><activityandroid:name=".MainActivity"android:label="@string/app_name"android:theme="@style/AppTheme.NoActionBar"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>