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. 资料整理:基于node push server实现push notification

    chat example based on ionic/ socket.io/ redis https://github.com/jbavari/ionic-socket.io-redis-chat ...

  2. Respone笔记

    1 设置定时刷新的头 //设置定时刷新的头 response.setHeader("refresh", "5;url=http://www.baidu.com" ...

  3. nexus开机启动

    在/etc/init.d目录下创建nexus文件 #!/bin/bash #chkconfig: #description:nexus3 #processname:nexus3 export JAVA ...

  4. Ubuntu apache

    Linux系统为Ubuntu 1. 启动apache服务 # /etc/init.d/apache2 start 2. 重启apache服务 # /etc/init.d/apache2 restart ...

  5. Scrapy框架学习(二)Scrapy入门

    接下来以爬取quote.toscrape.com为例完成一遍Scrapy的抓取流程. 首先创建一个Scrapy项目.打开命令行,输入以下命令: scrapy startproject projectn ...

  6. HDU 5701 ——中位数计数——————【思维题】

    中位数计数 Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Subm ...

  7. android和Linux下getopt的差别

    1. Linux下如果找不到相对应的参数,则会跳过继续找下一个 Android下如果找不到则会直接返回-1,跳出来 2. Linux下通过getopt后会把找到的元素放到数组的前面,没找到的往后移动( ...

  8. 查找正序排列的List中缺失的日期数据的一个算法

    Code: public List<DateTime> getMissDateData() { DateTime[] keys = { DateTime.Now.AddDays(-5), ...

  9. C++命名空间使用代码

    namesp.h #pragma once #include <string> namespace pers { using namespace std; struct Person { ...

  10. Vue-[v-model]理解示例

    对应文档节点: https://vuefe.cn/v2/guide/components.html#Customizing-Component-v-model <body> <div ...