Android crash 日志捕获

来源:互联网 发布:淘宝店铺页头怎么设置 编辑:程序博客网 时间:2024/04/28 00:27

为了对已发布程序进行跟踪,通常会对程序的行为做一些记录并上传到server,一般会记录用户行为已方便更好的发进设计流程和记录程序crash日志,以便在后续版本中改正程序的错误,看了些文章也做了几个Demo,把自己的理解简单写一下。


1. 给线程设置一个自己的异常处理函数(Thread.setDefaultUncaughtExceptionHandler(MyHandler))。

这个方法原来的Java语言里面就有,我原来以为这个方法是改变当前线程的 exception handler,写了一个程序测试了下,发现在一个新建的Thread里面抛出一个异常也能被捕获,表示它改变了整个虚拟机线程的exception handler。现在主流的处理方法是给APP创建一个 MyApplication extends Application,重写基类的onCreate方法,并在此方法内对线程设置自己的handler,并在androidmanifest.xml文件中指定当前的app name为自己写的application类。示例代码如下:


public class DfApplicationextends Application

{

Thread.UncaughtExceptionHandler mDefaultHandler

public void onCreate()

{

super.onCreate();

System.out.println("my app create");

mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

Thread.setDefaultUncaughtExceptionHandler(new MyHandler(this.getApplicationContext()));

}

}


<manifestxmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.exceptionstudy"

    android:versionCode="1"

    android:versionName="1.0">


    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="15"/>


    <application

        android:icon="@drawable/ic_launcher"

        android:name="com.df.app.DfApplication"

        android:label="@string/app_name"

        android:theme="@style/AppTheme">

        <activity

            android:name=".MainActivity"

            android:label="@string/title_activity_main">

。。。。。。

当然这种方法不是必须的,因为上面也说到了,无论在哪里设置,都是对整个虚拟机的线程设置,也有不少人是在自己的Activity中进行此操作。不过建议还是放在application类中处理,从抽象上更好理解----这个设置是针对整个应用的。


2.利用ACRA(application crash report for android),是google的一个开源项目,引入它的包,可以将crash log发送到自己的google文档,官方文档有详细说明。http://code.google.com/p/acra/




参考:http://www.eoeandroid.com/blog-23755-2661.html