Android小技巧(一):实现捕获应用的运行时异常

来源:互联网 发布:手机snapseed剪影知乎 编辑:程序博客网 时间:2024/06/04 18:45

转载请注明出处!本博客地址:http://blog.csdn.net/mylzc

由于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. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {//给主线程设置一个处理运行时异常的handler@Overridepublic 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() {@Overridepublic 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>

转载请注明出处!本博客地址:http://blog.csdn.net/mylzc

原创粉丝点击