通过实现Thread.UncaughtExceptionHandler接口来自定义异常处理
首先重写uncaughtException()方法,在这个方法中可以具体的处理异常,例如写本地文件,上传异常到服务器等。在方法尾部记得调用默认的异常处理方法Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t,e);若没有调用,程序可能无法正常结束。
在application中调用Thread.setDefaultUncaughtExceptionHandler();注册这个类以正常使用。
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String DIRECTORY_NAME = "JNIDemo";
private static CrashHandler instance;
private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
private Context context;
private String fileName = "CrashLog.txt";
public static CrashHandler getInstance(){
if(instance == null){
synchronized(CrashHandler.class){
if(instance == null){
instance = new CrashHandler();
return instance;
}
}
}
return instance;
}
public void register(Context context){
this.context = context;
defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
new Thread(new Runnable()
{
@Override
public void run()
{
if(context!=null)
{
Looper.prepare();
Toast.makeText(context,"程序崩溃了:( \n崩溃日志已保存到"+"",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
}).start();
FileOutputStream fileOutputStream = null;
try {
// File dir = new File(Environment.getExternalStorageDirectory()+"/"+DIRECTORY_NAME);
// if (!dir.exists()){
// dir.mkdirs();
// }
File file = new File(Environment.getExternalStorageDirectory()+"/"+fileName);
if(!file.exists()){
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(e.getCause().toString().getBytes());
fileOutputStream.flush();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}finally {
if (fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
if(defaultUncaughtExceptionHandler!=null){
Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t,e);
}
}
}