package com.oval.cft;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone; import com.oval.cft.constant.OvalConstant; import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast; /**
* 自定义系统的Crash捕捉类,用Toast替换系统的对话框
* 将软件版本信息,设备信息,出错信息保存在SD卡中,可以上传到服务器中
* @author Jackyin
*
*/
public class CustomCrashHandler implements UncaughtExceptionHandler {
private static final String TAG = "Activity";
private Context mContext;
@SuppressWarnings("unused")
private static final String SDCARD_ROOT = Environment.getExternalStorageDirectory().toString();
private static CustomCrashHandler mInstance = new CustomCrashHandler(); private CustomCrashHandler() {
} /**
* 单例模式,保证只有一个CustomCrashHandler实例存在
* @return
*/
public static CustomCrashHandler getInstance() {
return mInstance;
} /**
* 异常发生时,系统回调的函数,我们在这里处理一些操作
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// 将一些信息保存到SDcard中
savaInfoToSD(mContext, ex);
// 提示用户程序即将退出
showToast(mContext, "很抱歉,程序遭遇异常,即将退出!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);
ExitAppUtils.getInstance().exit(); } /**
* 为我们的应用程序设置自定义Crash处理
*/
public void setCustomCrashHanler(Context context) {
mContext = context;
Thread.setDefaultUncaughtExceptionHandler(this);
} /**
* 显示提示信息,需要在线程中显示Toast
* @param context
* @param msg
*/
private void showToast(final Context context, final String msg) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Looper.loop();
}
}).start();
} /**
* 获取一些简单的信息,软件版本,手机版本,型号等信息存放在HashMap中
* @param context
* @return
*/
private HashMap<String, String> obtainSimpleInfo(Context context) {
HashMap<String, String> map = new HashMap<String, String>();
PackageManager mPackageManager = context.getPackageManager();
PackageInfo mPackageInfo = null;
try {
mPackageInfo = mPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
} catch (NameNotFoundException e) {
e.printStackTrace();
} map.put("versionName", mPackageInfo.versionName);
map.put("versionCode", "" + mPackageInfo.versionCode); map.put("MODEL", "" + Build.MODEL);
map.put("SDK_INT", "" + Build.VERSION.SDK_INT);
map.put("PRODUCT", "" + Build.PRODUCT); return map;
} /**
* 获取系统未捕捉的错误信息
* @param throwable
* @return
*/
private String obtainExceptionInfo(Throwable throwable) {
StringWriter mStringWriter = new StringWriter();
PrintWriter mPrintWriter = new PrintWriter(mStringWriter);
throwable.printStackTrace(mPrintWriter);
mPrintWriter.close(); Log.e(TAG, mStringWriter.toString());
return mStringWriter.toString();
} /**
* 保存获取的 软件信息,设备信息和出错信息保存在SDcard中
* @param context
* @param ex
* @return
*/
private String savaInfoToSD(Context context, Throwable ex) {
String fileName = null;
StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : obtainSimpleInfo(context).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append(" = ").append(value).append("\n");
} sb.append(obtainExceptionInfo(ex)); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File dir = new File(OvalConstant.APP_EXCEPTION_DIRECTORY);
if (!dir.exists()) {
dir.mkdir();
} try {
fileName = dir.toString() + File.separator + paserTime(System.currentTimeMillis()) + ".log";
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(sb.toString().getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} return fileName; } /**
* 将毫秒数转换成yyyy-MM-dd-HH-mm-ss的格式
* @param milliseconds
* @return
*/
@SuppressLint("SimpleDateFormat")
private String paserTime(long milliseconds) {
System.setProperty("user.timezone", "Asia/Shanghai");
TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
TimeZone.setDefault(tz);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String times = format.format(new Date(milliseconds));
return times;
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressWarnings("unused")
@Override
public void onCreate() {
if (OvalConstant.Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
}
super.onCreate();
// 初始化应用异常处理
initCustomCrashHandler();
}
找到一个Android的异常处理的办法,经过测试可以使用,加到项目中。

androidcarsh的更多相关文章

随机推荐

  1. Oracle 行列转换函数pivot、unpivot的使用(二)

    一.行转列pivot 关键函数pivot,其用法如下 pivot(聚合函数 for 列名 in(类型)) select * from table_name pivot(max(column_name) ...

  2. Win32创建异形窗口

    大家都见过在windows下各种气泡窗口.输入法窗口以及其他一些窗口,这些窗口看起来不像传统的windows窗那样,上面是标题栏,下面是窗口的客户区.这些窗口形状各异,可以是一个多边形,一幅图,甚至是 ...

  3. $bzoj1014-JSOI2008$ 火星人$prefix$ $splay$ $hash$

    题面描述 火星人最近研究了一种操作:求一个字串两个后缀的公共前缀.比方说,有这样一个字符串:\(madamimadam\),我们将这个字符串的各个字符予以标号: 序号 1 2 3 4 5 6 7 8 ...

  4. Netflix Hystrix笔记

    maven引入 <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hyst ...

  5. ArrayList、Vector和LinkedList等的差别与用法(基础回顾)

    ArrayList 和Vector是采取数组体式格式存储数据,此数组元素数大于实际存储的数据以便增长和插入元素,都容许直接序号索引元素,然则插入数据要设计到数组元素移动等内存操纵,所以索引数据快插入数 ...

  6. python-入门教程(-)

    # hello worldprint("hello world") # 变量msg = "使用变量"print(msg) # 字符串大小写变换(仅针对英文)na ...

  7. 项目管理系列--从零开始Code Review[转]

    从零开始Code Review 这篇帖子不是通篇介绍Code Review的方法论, 而是前大段记录了我们团队怎么从没有这个习惯到每天都进行review的过程, 后小段给出了我的一些建议. 希望能对诸 ...

  8. window.location.href.substr(window.location.href.length - 6)

    if (window.location.href.substr(window.location.href.length - 6) == "flag=1") { var tOptio ...

  9. Centos 从零开始 (三)

    8:连接阿里云. 需要用到 ssh指令进行远程登陆 [root@localhost ~]# service sshd start #如果没开启服务的话,需要开启服务. [root@localhost  ...

  10. 从代码层读懂 Java HashMap 的实现原理

    概述 Hashmap继承于AbstractMap,实现了Map.Cloneable.Java.io.Serializable接口.它的key.value都可以为null,映射不是有序的.Hashmap ...