前言
看公司以前的项目,发现了一个类继承了UncaughtExceptionHandler接口,稍微研究了一下,它的作用是当程序发生Uncaught异常的时候,有该类来接管程序,并记录(也可以远程发送),最近很久没发过文章(加班,TI7...),在这里总结一哈。
首先
关于这个类是用来做什么的,很多小伙伴在调试程序的时候都会出现AndroidRuntime的问题,然后系统会跳出一个dialog告诉你蹦了。而你并不知道程序具体蹦在哪里,且用户看到这个dialog,也会觉得自己的体验非常的差,再且当我们的程序已经投入使用,你并不能保证已经完全修复了程序的bug。这个时候就需要我们的CrashHandler(implements Thread.UncaughtExceptionHandler)来帮助我们完善这个功能了。
public class CrashHandler implements Thread.UncaughtExceptionHandler {}
然后
具体实现,一边贴代码一边理解
//系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler;
//CrashHandler实例
private static CrashHandler INSTANCE = new CrashHandler();
//程序的Context对象
private Context mContext;
//用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();
//用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
构造函数,这里用的是private,这样其他的类就不能直接调用该类生成新的对象,也就避免了同一个类被反复创建的情况,这种情况,该类只有一个对象实例。
private CrashHandler(){
}
//调用
public static CrashHandler getInstance(){
return INSTANCE;
}
public void init(Context context){
mContext=context;
//获取系统默认的UncaughtException处理器
mDefaultHandler=Thread.getDefaultUncaughtExceptionHandler();
//设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
重写uncaughtException方法,如果用户没有处理则让系统默认的异常处理器来处理:
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
//退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
自定义错误处理,收集错误信息 发送错误报告等操作均在此完成,true:如果处理了该异常信息;否则返回false.
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//使用Toast来显示异常信息
new Thread() {
@SuppressLint("ShowToast")
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.",Toast.LENGTH_SHORT);
Looper.loop();
}
}.start();
//保存日志文件
final String logFileName = saveCrashInfo2File(ex);
return true;
}
返回文件名称:
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = "/sdcard/crash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
最后:
获取了log还是要返还给程序员改bug的,这里选择用Email的形式(项目里的方法,也可以直接放到指定服务器,方法就不罗嗦了),直接上代码:
public class SendEmailUtils {
/**
* 邮件发送程序
*
* 接收邮件的address
* @param subject
* 邮件主题
* @param content
* 邮件内容
* @param attachmentPath
* 附件路径
* @param attachmentName
* 附件名称
* @throws Exception
*/
public static void sendEmail(String toAddress, String subject, String content ,String attachmentPath,String attachmentName) throws Exception, MessagingException {
Log.i("name","name="+subject);
Log.i("content", content);
String host = "smtp.163.com";
String address = "logfeedback@163.com";
String from = "logfeedback@163.com";
String password = "LogFdbk2016zf";// 密码
if ("".equals(toAddress) || toAddress == null) {
toAddress = "logfeedback@163.com";
}
String port = "25";
SendEmail(host, address, from, password, toAddress, port, subject, content,attachmentPath,attachmentName);
}
/**
* 邮件发送程序
*
* @param host
* 邮件服务器 如:smtp.qq.com
* @param address
* 发送邮件的地址 如:878458730@qq.com
* @param from
* 来自: wsx2miao@qq.com/也就是发件人地址
* @param password
* 您的邮箱密码
* @param to
* 接收人
* @param port
* 端口(QQ:25/sina:25/163:25)
* @param subject
* 邮件主题
* @param content
* 邮件内容
* @param attachmentPath
* 附件路径
* @param attachmentName
* 附件名称
* @throws Exception
*/
public static void SendEmail(String host, String address, String from, String password, String to, String port, String subject, String content,String attachmentPath,String attachmentName) throws Exception {
Multipart multiPart;
String finalString = "";
//附件地址
// String affix="/mnt/sdcard/oppo.mp4";
// String affixName="oppo.mp4";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", address);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
Log.i("Check", "done pops");
Session session = Session.getDefaultInstance(props, null);
DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setDataHandler(handler);
Log.i("Check", "done sessions");
multiPart = new MimeMultipart();
//添加附件
BodyPart messageBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(new DataHandler(source));
//添加接收人地址to代表接收人地址
InternetAddress toAddress = new InternetAddress(to);
messageBodyPart.setFileName(attachmentName);
multiPart.addBodyPart(messageBodyPart);
message.addRecipient(Message.RecipientType.TO, toAddress);
Log.i("Check", "added recipient");
message.setSubject(subject);
// message.setContent(multiPart);
message.setText(content);
//将multipart对象放到message中
message.setContent(multiPart);
//保存邮件
message.saveChanges();
Log.i("check", "transport");
Transport transport = session.getTransport("smtp");
Log.i("check", "connecting");
transport.connect(host, address, password);
Log.i("check", "wana send");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Log.i("check", "sent");
}
}
说一下,上述方法类import的是javax的包,Android studio在挂在包的时候将jdk根部的整个包挂在过去。至于具体的效果和细节,还是需要动手实践的。