public class CrashHandler implements Thread.UncaughtExceptionHandler {
private Context mContext;
private Thread.UncaughtExceptionHandler exceptionHandler;
/**
* 单例模式
*/
private static CrashHandler crashHandler = null;
private CrashHandler() {
}
public static CrashHandler getInstance() {
if (crashHandler == null) {
synchronized (CrashHandler.class) {
crashHandler = new CrashHandler();
}
}
return crashHandler;
}
/**
* 初始化
* @param context
*/
public void init(Context context) {
mContext = context;
exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
/**
* 判断是否有异常
* 有异常调用
*/
if (hanlderException(e) && crashHandler != null) {
crashHandler.uncaughtException(t, e);
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
Log.i("xxx", "error: " + e1);
}
}
}
/**
* 判断异常
*
* @param e
* @return
*/
private boolean hanlderException(final Throwable e) {
if (e == null) {
return false;
}
/**
* 手动处理
*/
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Log.i("xxx", "error: " + e.toString());
Toast.makeText(mContext, "程序开小差了...", Toast.LENGTH_SHORT).show();
/**
* 写入SD卡
*/
String sdFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/crash.txt";
File file = new File(sdFile);
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(e.toString().getBytes());
outputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
Looper.loop();
}
}).start();
return true;
}
}
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//初始化CrashHandler
CrashHandler.getInstance().init(this);
}
}