【Android实战】Android中处理崩溃异常
public class MainActivity extends ActionBarActivity {
public CrashApplication application;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
application = (CrashApplication) getApplication();
application.addAct(this);
Button button = null;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class CrashApplication extends Application {
List<Activity> activityList = new ArrayList<Activity>();
@Override
public void onCreate() {
super.onCreate();
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
public void addAct(Activity a) {
activityList.add(a);
}
public void delAct(Activity a) {
activityList.remove(a);
}
public void finishActs() {
for (Activity a : activityList) {
if (null != a) {
a.finish();
}
}
android.os.Process.killProcess(android.os.Process.myPid());
}
}
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;
// 用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();
// 用于格式化日期,作为日志文件名称的一部分
private SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
/** 保证仅仅有一个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);
}
/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 假设用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
// 退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
// 退出程序
((CrashApplication) mContext).finishActs();
}
;
}
/**
* 自己定义错误处理,收集错误信息 发送错误报告等操作均在此完毕.
*
* @param ex
* @return true:假设处理了该异常信息;否则返回false.
*/
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();
// 收集设备參数信息
collectDeviceInfo(mContext);
// 保存日志文件
saveCrashInfo2File(ex);
return true;
}
/**
* 收集设备參数信息
*
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ?
"null"
: pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}
/**
* 保存错误信息到文件里
*
* @param ex
* @return 返回文件名称称,便于将文件传送到server
*/
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;
}
}
【Android实战】Android中处理崩溃异常的更多相关文章
- Android中处理崩溃异常和记录日志(转)
现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不定就出现崩溃的现象,开发者个人不可能购买所有设备逐个调试,所以在程序发布出去之后,如果出现了崩溃现象,开 ...
- Android中处理崩溃异常
转自:http://my.eoe.cn/817027/archive/17997.html 大家都知道,现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不 ...
- Android中处理崩溃异常和记录日志
大家都知道,现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不定就出现崩溃的现象,开发者个人不可能购买所有设备逐个调试,所以在程序发布出去之后,如果出现了 ...
- Android中处理崩溃异常CrashHandler
来源:http://blog.csdn.net/liuhe688/article/details/6584143 大家都知道,现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程 ...
- 【转】Android中处理崩溃异常
大家都知道,现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不定就出现崩溃的现象,开发者个人不可能购买所有设备逐个调试,所以在程序发布出去之后,如果出现了 ...
- Android中处理崩溃异常 (转)
大家都知道,现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不定就出现崩溃的现象,开发者个人不可能购买所有设备逐个调试,所以在程序发布出去之后,如果出现了 ...
- 【转】Android 中处理崩溃异常并重启程序出现页面重叠的问题
原文地址:http://blog.csdn.net/jiang547860818/article/details/53641113 android开发中经常会遇到程序异常,而已常常会遇到一出现异常AP ...
- 【Android开发笔记】程序崩溃异常总结
广播注册相关(broadcastReceiver) 没有注册广播就注销广播 注册广播但未注销广播 注册广播后重复注销广播 解决办法: 添加一个布尔变量,注册广播后为true,若为true在执行注销,注 ...
- Android开发之处理崩溃异常
众所周知,android的设备千差万别,难免会发生崩溃异常等现象,这个时候就需要捕获哪些崩溃异常了,也就是捕获崩溃异常的相关信息,并记录下来,这样一来方便开发人员和测试人员的分析与调试. 1.首先我们 ...
随机推荐
- linux中init.d文件夹的说明
一.简单说明 /etc/init.d 是 /etc/rc.d/init.d 的软链接(soft link).可以通过 ll 命令查看. ls -ld /etc/init.d lrwxrwxrwx. r ...
- 帆软报表和jeecg的进一步整合--ajax给后台传递map类型的参数
下面是页面代码: <%@ page language="java" contentType="text/html; charset=UTF-8" page ...
- Ubuntu下python两个版本的切换
最近在Ubuntu16.04安装了python3.5还有系统自带的python2.7.13,总结一下不同版本的切换问题. alias:别名 bashrc:个人配置文件 一.修改Python版本(针对用 ...
- 关于TCP/IP与数据传输
一.TCP/IP的具体含义: 从字面意思来讲,很多人会认为TCP/IP是指TCP与IP这两种协议.有时确实也可以说是这两种协议,但是大部分情况下所说的是利用IP进行通信时所必须用到的协议群的统称.具体 ...
- Centos设置静态IP及修改Centos配置文件的方法
通常,如果我们想更改主机地址为静态地址或者更改主机名,需要修改的几个文件包括: /etc/sysconfig/network Centos设置主机名和网络配置 /etc/sysconfig/netwo ...
- 算法导论--装备线调度(升序&&降序输出)
题意就先不用讲了吧,感觉自己还没有掌握核心的东西. //心得 //如何保持路径,递归的实现 #include<iostream> #include<cstdio> #inclu ...
- [小技巧]Mac上chrome打开触控板双指前进后退功能
Orz,本以为是默认开启的,结果发现并不是,从系统里找了半天发现没找到-就搜了一下,原来可以命令开启来 defaults write com.google.Chrome AppleEnableSwip ...
- python2安装pymongo
wget --no-check-certificate https://pypi.python.org/packages/source/p/pymongo/pymongo-2.6.3.tar.gz#m ...
- 配置maven为阿里云加速
<repositories> <repository> <id>nexus-aliyun</id> <name>Nexus aliyun&l ...
- Python获取时间范围内日期列表和周列表的函数
1.获取日期列表 # -*- coding=utf-8 -*- import datetime def dateRange(beginDate, endDate): dates = [] dt = d ...