您的位置:首页 > 运维架构

安卓中的质量监控CrashHandler implements UncaughtExceptionHandler

2016-05-02 01:25 337 查看
何为质量监控,当我们的项目上线之后,用户下载到自己手机上,程序出现了没有捕获的异常,这些异常怎么解决,让程序崩溃吗,不能,在这种情况下,就用到了我们的质量监控。

捕获那些没有 try catch 的异常

需要自己的类实现UncaughtExceptionHandler 接口(未捕获异常handler接口)

捕获到异常信息之后 需要提示用户,(给客户提示信息,本质是更新界面控件,在工作线程中需要用looper 才能更新UI)需要把异常信息发送到服务器,以便下次升级版本的时候,修改异常。

系统强制KILL 掉应用程序,然后过两秒重新启动应用程序。

/**
* 处理程序 错误
*
* @author 甄
*
*/
public class CrashHandler implements UncaughtExceptionHandler {

TApplication tApplication;

public CrashHandler(TApplication tApplication) {
super();
this.tApplication = tApplication;
}

/**
* 出异常了,没有加try catch的异常 不能加断点
*/
@Override
public void uncaughtException
(Thread thread, Throwable ex) {

//得异常信息发到网上服务器
//String string=ex.getMessage(); 这句信息太少,让程序员无法判断什么异常
//用下面的这个  把异常信息转化成字符串 详细的信息
StringWriter stringWriter=new StringWriter();
PrintWriter printWriter=new PrintWriter(stringWriter);
ex.printStackTrace(printWriter);
String string=stringWriter.toString();
Log.i("CrashHandler", "出错了4 "+string);
// 启工作线程,toast是界面控件
// 工作线程不能更新ui
new Thread() {
public void run() {
// show 用到队列,主线程有looper,取消息放队列
// 在这个工作线程中 需要自己手动添加looper
Looper.prepare();
Toast.makeText(tApplication, "网络不稳定,程序即将重启", Toast.LENGTH_LONG).show();
Looper.loop();
};
}.start();

try {
Thread.currentThread().sleep(2000);
} catch (Exception e) {
// TODO: handle exception
}

Intent intent = new Intent(tApplication, MainActivity.class);
// 不执行
// tApplication.startActivity(intent);
// 当前tash出异常,创建新的task
PendingIntent pendingIntent = PendingIntent.getActivity(tApplication,
100, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

// 过一会儿执行pendingIntent  过两秒之后 启动MainActivity.class
//获取闹钟管理器,通过获得系统服务 获得闹钟管理器
AlarmManager alarmManager = (AlarmManager) tApplication.getSystemService(Context.ALARM_SERVICE);
//设置闹钟管理器的set  设置睡眠2秒 再启动
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 2000,pendingIntent);
//调用自己类tApplication 中自己写的finish()方法   销毁进程。以便启动新的进程
tApplication.finish();

}

}


MyApplication 中创建finish() 方法,设置默认的捕获未捕获异常的handler

//在manifest.xml注册
public class TApplication extends Application{
ArrayList<Activity> activityList=new ArrayList();
public void finish()
{
for(Activity activity:activityList)
{
activity.finish();
}
//android.os    系统强制杀死应用程序
Process.killProcess(Process.myPid());
}
//全局
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
CrashHandler crashHandler=new CrashHandler(this);
//设置默认的捕获未捕获异常的handler
Thread.setDefaultUncaughtExceptionHandler(crashHandler);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: