Android小技巧:实现捕获应用的运行时异常 分类: Android其他 2015-06-23 12:26 12人阅读 评论(0) 收藏

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

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

TestActivity.java

view plain
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 { 
     
 
 
    @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
view plain
 
http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
   
        android:layout_height="wrap_content" android:text="@string/hello" /> 
   
        android:text="点击按钮触发运行时异常" android:layout_height="wrap_content" 
        android:layout_weight="1" android:gravity="top"> 
     
 

作者“lzc的专栏”

posted @ 2015-06-23 12:26  leansmall  阅读(123)  评论(0编辑  收藏  举报