转载博客:http://blog.csdn.net/i_lovefish/article/details/17719081

以下为异常捕捉处理代码:  
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; 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; /**
* UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.
*
* 需要在Application中注册,为了要在程序启动器就监控整个程序。
*/
public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "CrashHandler"; //系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler;
//CrashHandler实例
private static CrashHandler instance;
//程序的Context对象
private Context mContext;
//用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>(); //用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); /** 保证只有一个CrashHandler实例 */
private CrashHandler() {} /** 获取CrashHandler实例 ,单例模式 */
public static CrashHandler getInstance() {
if(instance == null)
instance = new CrashHandler();
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);
}
} /**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//收集设备参数信息
collectDeviceInfo(mContext); //使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
//保存日志文件
saveCatchInfo2File(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 返回文件名称,便于将文件传送到服务器
*/
private String saveCatchInfo2File(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 = "/mnt/sdcard/crash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
//发送给开发人员
sendCrashLog2PM(path+fileName);
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
} /**
* 将捕获的导致崩溃的错误信息发送给开发人员
*
* 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。
*/
private void sendCrashLog2PM(String fileName){
if(!new File(fileName).exists()){
Toast.makeText(mContext, "日志文件不存在!", Toast.LENGTH_SHORT).show();
return;
}
FileInputStream fis = null;
BufferedReader reader = null;
String s = null;
try {
fis = new FileInputStream(fileName);
reader = new BufferedReader(new InputStreamReader(fis, "GBK"));
while(true){
s = reader.readLine();
if(s == null) break;
//由于目前尚未确定以何种方式发送,所以先打出log日志。
Log.i("info", s.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{ // 关闭流
try {
reader.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

针对异常的捕捉要进行全局监控整个项目,所以要将其在Application中注册(也就是初始化):

import android.app.Application;  

public class CrashApplication extends Application {  

    @Override
public void onCreate() {
super.onCreate();
CrashHandler catchHandler = CrashHandler.getInstance();
catchHandler.init(getApplicationContext());
}
}

现在模拟一个空指针异常:

import android.app.Activity;
import android.os.Bundle; public class CatchExceptionLogActivity extends Activity {
/** Called when the activity is first created. */
private String s;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println(s.equals("hello")); // s没有进行赋值,所以会出现NullPointException异常
}
}

别忘了在配置文件中对Application进行注册:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.forms.catchlog"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
<span style="color:#ff0000;">android:name=".CrashApplication"></span>
<activity
android:label="@string/app_name"
android:name=".CatchExceptionLogActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>
添加异常捕获之后的日志提示

由于Android设备各异,第三方定制的Android系统也非常多,我们不可能对所有的设备场景都进行测试,因而开发一款完全无bug的应用几乎是不可能的任务,那么当应用在用户的设备上Force Close时,我们是不是可以捕获这个错误,记录用户的设备信息,然后让用户选择是否反馈这些堆栈信息,通过这种bug反馈方式,我们可以有针对性地对bug进行修复。

当我们的的应用由于运行时异常导致Force Close的时候,可以设置主线程的UncaughtExceptionHandler,实现捕获运行时异常的堆栈信息。同时用户可以把堆栈信息通过发送邮件的方式反馈给我们。下面是实现的代码:

代码下载请按此

例子:点击按钮后,会触发一个NullPointerException的运行时异常,这个例子实现了捕获运行时异常,发送邮件反馈设备和堆栈信息的功能。

界面1(触发运行时异常)

  

界面2(发送堆栈信息)

  

TestActivity.java
package com.zhuozhuo; 

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler; import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView; public class TestActivity extends Activity {
/** Called when the activity is first created. */ @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {//给主线程设置一个处理运行时异常的handler @Override
public void uncaughtException(Thread thread, final Throwable ex) { StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw); StringBuilder sb = new StringBuilder(); sb.append("Version code is ");
sb.append(Build.VERSION.SDK_INT + "\n");//设备的Android版本号
sb.append("Model is ");
sb.append(Build.MODEL+"\n");//设备型号
sb.append(sw.toString()); Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
sendIntent.setData(Uri.parse("mailto:csdn@csdn.com"));//发送邮件异常到csdn@csdn.com邮箱
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "bug report");//邮件主题
sendIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());//堆栈信息
startActivity(sendIntent);
finish();
}
}); findViewById(R.id.button).setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Integer a = null;
a.toString();//触发nullpointer运行时错误 }
}); }
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<EditText android:id="@+id/editText1" android:layout_width="match_parent"
android:text="点击按钮触发运行时异常" android:layout_height="wrap_content"
android:layout_weight="1" android:gravity="top"></EditText>
<Button android:text="按钮" android:id="@+id/button"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"></Button>
</LinearLayout>

Android 对程序异常崩溃的捕捉的更多相关文章

  1. ArcGIS for Android 10.1.1API 中文标注导致程序异常崩溃问题

    1.前言 问题:在部分Android机型中使用ArcGIS for Android 10.1.1 API 中文标注导致程序异常崩溃. 说明:手里有两台机器一台是Nexus4,原生系统,版本4.4.4, ...

  2. 程序异常崩溃后用windbg辅助调试解决的经验 以及 堆栈问题调试经验

    1,程序异常崩溃后用windbg辅助调试解决的经验  状况:我的程序调用别人的库做 文件写入工作. 在这一过程中出现异常,程序崩溃. 经反复检查,认为自己的程序没有错,但无法判断在别人库里哪里有错. ...

  3. android捕获程序异常退出

    今天看到迅雷动漫里面一个CrashHandler 的类,我猜是崩溃处理类.进去一看.果然.顺便学习一下. Android系统的"程序异常退出",给应用的用户体验造成不良影响.为了捕 ...

  4. android在程序崩溃时Catch异常并处理

    Android系统的"程序异常退出",给应用的用户体验造成不良影响.为了捕获应用运行时异常并给出友好提示,便可继承UncaughtExceptionHandler类来处理.通过Th ...

  5. Android 应用程序崩溃日志捕捉

    程序崩溃是应用迭代中不可避免的问题,即使有着5年或者10年经验的程序猿也无法完全保证自己的代码没有任何的bug导致崩溃,现在有一些第三方平台可以帮助我们搜集应用程序的崩溃,比如友盟,详情如下图 虽然能 ...

  6. Android平台程序崩溃的类型及原因列举

    Android平台程序崩溃大家都应该遇到过,force close和ANR应该是大家遇到较多的. 这里把Android平台程序崩溃的各种类型做一个简述和原因列举. 1.ANR(可见ANR): 发生场景 ...

  7. 【Android开发经验】我们要友好的告诉用户,程序要崩溃了

        转载请注明出处:http://blog.csdn.net/zhaokaiqiang1992     尽管我们的程序在正式上线之前,都会经过严格的測试.从而保证程序的健壮性和良好的用户体验,可是 ...

  8. Android将应用程序的崩溃信息如何保存到本地文件,并上传服务器

    导语:最近实在是太忙了,没有怎么更新公众号,也没有怎么认真去写一些内容,在这里先给关注我的朋友说一声抱歉,可能在接下来的一段时间,还是很忙,但是我会争取抽空多分享一下技术文章,给大家看,共同进步,也希 ...

  9. Android系统的“程序异常退出”[转]

    在应用运行过程中,有很多异常可能会发生,而我们希望在异常发生的时候第一时间的保存现场. 如何处理未捕获的异常呢? 首先我们要实现一个接口  java.lang.Thread.UncaughtExcep ...

随机推荐

  1. 栈的JS实现

    栈,是一种特殊的线性表,其插入及删除的操作都在线性表的同一端进行.这一端称为栈顶,另一端称为栈底.就类似于餐厅里的一摞盘子,后放的盘子在上方,也会先被人拿走.栈具有"后进先出"的逻 ...

  2. 弱省互测#0 t1

    题意 给一个\(N \times M\)的01网格,1不能走,从起点\((1, 1)\)走到\((N, M)\),每次只能向下或向右走一格,问两条不相交的路径的方案数.(n, m<=1000) ...

  3. knockoutjs扩展与使用

    原来考虑使用avalon2.0 经过一周的试验,能力不够,用不起来.最终使用了knockout-3.4.js <!DOCTYPE html> <html> <head&g ...

  4. Java_位运算(移位、位与、或、异或、非)

    public class Test { public static void main(String[] args) { // 1.左移( << ) // 0000 0000 0000 0 ...

  5. 不使用return false阻止event默认行为

    当我们点击一个a标签时,如果这个标签的href指向了另一个地址,那么浏览器会默认跳转到此地址.在页面中,有时我们需要触发点击事件,但是又不想触发默认行为,就需要阻止event的默认行为了. 常规做法 ...

  6. 速度极快的导出excel

    public class Export2Excel { #region [导出文件,使用文件流] /// <summary> /// 导出文件,使用文件流.该方法使用的数据源为DataTa ...

  7. c#文本转语音以及语音阅读小实例

    c#实现语音阅读以及文本转语音文件是基于c#的一个类库(SpeechSynthesizer )实现的,使用该类必须要添加引用using System.Speech.Synthesis;直接是无法添加引 ...

  8. python方法中的self

    前几天在写一个c作业时,突发奇想,在结构体中加入函数指针, 像这样: struct People { int _age; int (*age)(); }people; 这样调用时就可以 people. ...

  9. GeoIP Legacy City数据库安装说明

    Here is a brief outline of the steps needed to install GeoIP Legacy City on Linux/Unix. The installa ...

  10. Java程序开发.邱加永2.1节

    by2016.9.8 2.7.1 一维数组 1. 声明 int[] m: char[] c: double[] d:   2. 创建 数组声明之后还不能使用,m = new int[10]: c = ...