import android.content.Context;
import android.os.Environment;
import android.os.Process;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
* 这个就是用来捕获项目的所有异常监听
*/
public class MyUncaughtException implements Thread.UncaughtExceptionHandler {
private static Context mContext;

private MyUncaughtException() {
}

private static class HolderUncaugh {
private static final MyUncaughtException uncaught = new MyUncaughtException();
}

public static MyUncaughtException getInstance(Context context) {
mContext = context;
return HolderUncaugh.uncaught;
}

//有异常了
@Override
public void uncaughtException(Thread t, Throwable e) {
Log.e("异常", e.getMessage());

File file = new File(Environment.getExternalStorageDirectory() + "/a.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
// PrintWriter pw = new PrintWriter(file)
try {
FileWriter fw = new FileWriter(file);
fw.write(e.getMessage());
fw.flush();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}


//杀死当前进程
Process.killProcess(Process.myPid());

//推出当前程序
//System.exit(1);
}
}


//记得在Application进行注册
import android.app.Application;

/**
* 一个项目里面有多少个Context
* Activity的个数+Service个数+ 1(application)
* Application代表整个项目的上下文对象
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//首先获取这个对象
MyUncaughtException instance = MyUncaughtException.getInstance(this);
//开始监听
Thread.setDefaultUncaughtExceptionHandler(instance);
}
}