Android Crash异常处理方法

来源:互联网 发布:sql数据库的备份和还原 编辑:程序博客网 时间:2024/06/06 01:20

写在前面

大家都知道,Android应用不可避免的会发生Crash,无论你的程序写的多完美,总是无法完全避免Crash的发生,可能是由于Android系统底层的Bug,也可能是由于不充分的机型适配或者是糟糕的网络状况。当Crash发生时,系统会Kill掉你的程序,表现就是闪退或者程序已停止运行,这对用户来说是很不友好的,也是开发者所不愿意看到的,更糟糕的是,当用户发生了Crash,开发者却无法得知程序为何Crash,即便你想去解决这个Crash,但是由于你无法知道用户当时的Crash信息,所以你也无能为力。是否真的这样呢,其实Android中有处理这类问题的方法,请看下面Thread类中的一个方法setDefaultUncaughtExceptionHandler。

/**     * Set the default handler invoked when a thread abruptly terminates     * due to an uncaught exception, and no other handler has been defined     * for that thread.     *     * <p>Uncaught exception handling is controlled first by the thread, then     * by the thread's {@link ThreadGroup} object and finally by the default     * uncaught exception handler. If the thread does not have an explicit     * uncaught exception handler set, and the thread's thread group     * (including parent thread groups)  does not specialize its     * <tt>uncaughtException</tt> method, then the default handler's     * <tt>uncaughtException</tt> method will be invoked.     * <p>By setting the default uncaught exception handler, an application     * can change the way in which uncaught exceptions are handled (such as     * logging to a specific device, or file) for those threads that would     * already accept whatever "default" behavior the system     * provided.     *     * <p>Note that the default uncaught exception handler should not usually     * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause     * infinite recursion.     *     * @param eh the object to use as the default uncaught exception handler.     * If <tt>null</tt> then there is no default handler.     *     * @throws SecurityException if a security manager is present and it     *         denies <tt>{@link RuntimePermission}     *         ("setDefaultUncaughtExceptionHandler")</tt>     *     * @see #setUncaughtExceptionHandler     * @see #getUncaughtExceptionHandler     * @see ThreadGroup#uncaughtException     * @since 1.5     */    public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {         defaultUncaughtExceptionHandler = eh;     }
这个方法好像是可以设置系统的默认异常处理器,其实,这个方法就可以解决应用常见的Crash问题。当Crash发生的时候,我们可以捕获到异常信息,把异常信息存储到SD卡中,然后在合适的时机通过网络将Crash信息上传到服务器上,这样开发人员就可以分析用户Crash的场景从而在后面的版本中修复此类Crash。我们还可以在Crash发生时,弹出一个通知告诉用户程序Crash了,然后再退出,这样做比闪退要好一点。

使用方法

1.新建异常处理器类

CrashHandler.java

package com.jackie.appcrashhandler;import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.os.Build;import android.os.Environment;import android.os.Process;import android.util.Log;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;/** * Created by Jackie on 2017/1/3. * 异常处理器 */public class CrashHandler implements Thread.UncaughtExceptionHandler {    private static final String TAG = CrashHandler.class.getSimpleName();    private static final boolean DEBUG = true;    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/log/";    private static final String FILE_NAME = "crash";    //log文件的后缀名    private static final String FILE_SUFFIX = ".trace";    private static CrashHandler mCrashHandler;    //系统默认的异常处理(默认情况下,系统会终止当前的异常程序)    private Thread.UncaughtExceptionHandler mUncaughtExceptionHandler;    private Context mContext;    private CrashHandler() {    }    public static CrashHandler getInstance() {        if (mCrashHandler == null) {            synchronized (CrashHandler.class) {                if (mCrashHandler == null) {                    mCrashHandler = new CrashHandler();                }            }        }        return mCrashHandler;    }    public void init(Context context) {        //获取系统默认的异常处理器        mUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();        //将当前实例设为系统默认的异常处理器        Thread.setDefaultUncaughtExceptionHandler(this);        mContext = context.getApplicationContext();    }    /**     * 这个是最关键的函数,当程序中有未被捕获的异常,系统将会自动调用uncaughtException方法     * thread为出现未捕获异常的线程,ex为未捕获的异常,有了这个ex,我们就可以得到异常信息。     */    @Override    public void uncaughtException(Thread t, Throwable ex) {        try {            //导出异常信息到SD卡中            dumpExceptionToSDCard(ex);            //这里可以通过网络上传异常信息到服务器,便于开发人员分析日志解决bug            uploadExceptionToServer();        } catch (Exception e) {            e.printStackTrace();        }        //打印出当前调用栈信息        ex.printStackTrace();        //如果系统提供了默认的异常处理器,则交给系统去结束我们的程序,否则就由我们自己结束自己        if (mUncaughtExceptionHandler != null) {            mUncaughtExceptionHandler.uncaughtException(t, ex);        } else {            Process.killProcess(Process.myPid());        }    }    private void dumpExceptionToSDCard(Throwable ex) throws IOException {        //如果SD卡不存在或无法使用,则无法把异常信息写入SD卡        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            if (DEBUG) {                Log.d(TAG, "sdcard unmounted, skip dum exception");                return;            }        }        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(                new Date(System.currentTimeMillis()));        //以当前时间创建log文件        File file = new File(FILE_PATH + FILE_NAME + time + FILE_SUFFIX);        if (!file.exists()) {            file.createNewFile();        }        try {            PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file)));            //导出发生异常的时间            printWriter.println(time);            //导出手机信息            dumpPhoneInfo(printWriter);            printWriter.println();            //导出异常的调用栈信息            ex.printStackTrace(printWriter);            printWriter.close();        } catch (Exception e) {            Log.e(TAG, "dump crash info failed");        }    }    private void uploadExceptionToServer() {        //TODO Upload Exception Message To Your Web Server    }    private void dumpPhoneInfo(PrintWriter printWriter) throws            PackageManager.NameNotFoundException {        //应用的版本名称和版本号        PackageManager packageManager = mContext.getPackageManager();        PackageInfo packageInfo = packageManager.getPackageInfo(                mContext.getPackageName(), PackageManager.GET_ACTIVITIES);                printWriter.print("App Version: ");        printWriter.print(packageInfo.versionName);        printWriter.print('_');        printWriter.println(packageInfo.versionCode);        //Android版本号        printWriter.print("OS Version: ");        printWriter.print(Build.VERSION.RELEASE);        printWriter.print("_");        printWriter.println(Build.VERSION.SDK_INT);        //手机制造商        printWriter.print("Vendor: ");        printWriter.println(Build.MANUFACTURER);        //手机型号        printWriter.print("Model: ");        printWriter.println(Build.MODEL);        //CPU架构        printWriter.print("CPU ABI: ");        printWriter.println(Build.CPU_ABI);    }}

2.为UI线程添加默认异常事件Handler

这里涉及到在哪里添加的问题,从源码中注意到,这个defaultUncaughtHandler是Thread类中一个静态的成员,所以,按道理,我们为任意一个线程设置异常处理,所有的线程都应该能共用这个异常处理器,有一个观点是大家都认可的:就是为主线程也就是UI线程添加异常程序器。为了在UI线程中添加异常处理Handler,我们推荐大家在Application中添加而不是在Activity中添加。Application标识着整个应用,在Android声明周期中是第一个启动的,早于任何的Activity、Service等。

CrashApplication.java

package com.jackie.appcrashhandler;import android.app.Application;/** * Created by Jackie on 2017/1/3. * 异常处理Application */public class CrashApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        //在这里为应用设置异常处理程序,然后我们的程序才能捕获未处理的异常        CrashHandler crashHandler = CrashHandler.getInstance();        crashHandler.init(this);    }}
验证

MainActivity.java

package com.jackie.appcrashhandler;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button mBtnThrowException;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();    }    private void initView() {        mBtnThrowException = (Button) findViewById(R.id.btn_throw_exception);        mBtnThrowException.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.btn_throw_exception:                //在这里默认异常抛出情况,人为抛出一个运行时异常                throw new RuntimeException("自定义异常:这是自己抛出的异常");//                break;        }    }}

最后别忘了修改AndroidManifest.xml,添加下面的内容:


这里点击按钮,强制抛出一个异常,效果如如下:








0 0
原创粉丝点击