package com.zdsoft.crash;
import java.lang.Thread.UncaughtExceptionHandler;
import com.zdsoft.blp.MainActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class CrashHandler implements UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";
//系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler;
//CrashHandler实例
private static CrashHandler INSTANCE = new CrashHandler();
//程序的Context对象
private Context mContext;
/** 保证只有一个CrashHandler实例 */
private CrashHandler() {
}
/** 获取CrashHandler实例 ,单例模式 */
public static CrashHandler getInstance() {
return INSTANCE;
}
/**
* 初始化
*
* @param context
*/
public void init(Context context) {
mContext = context;
//获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
//程序闪退后的操作 如:保存闪退信息等
//退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
//重启程序
Intent intent = new Intent(mContext.getApplicationContext(),
MainActivity.class);
PendingIntent restartIntent = PendingIntent.getActivity(
mContext.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager mgr = (AlarmManager) mContext
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000,
restartIntent); // 2秒钟后重启应用
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
// Toast.makeText(mContext, "很抱歉,程序出现异常", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
//在此可执行其它操作,如获取设备信息、执行异常登出请求、保存错误日志到本地或发送至服务端
return true;
}
}
public class MyApplication extends Application{
//复制本包两类,并在配置文件 <application中 注册本类即可
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
}