CrashHandle捕获崩溃信息

程序的崩溃是不可避免的,我们有时需要手动捕捉这些崩溃信息,上传服务器。Android提供了扑捉crash的方法。在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.
     *
  public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
         defaultUncaughtExceptionHandler = eh;
     }

当Crash信息发生的时候,系统会会掉UncaughtExceptionHandler的uncaughtException方法,在这个方法中可以获取到新的异常信息。在这里我们可以处理我们的逻辑了。

下面的demo 是在手机端观看奔溃信息:

public class CrashHandle implements Thread.UncaughtExceptionHandler {

    Thread.UncaughtExceptionHandler mExceptionHandler;
    private Context mContext;

    public CrashHandle(Context context) {
        mContext = context;
        mExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        //系统默认处理
//        if (null != mExceptionHandler) {
//            mExceptionHandler.uncaughtException(t, e);
//        }
        StringWriter mStringWriter = new StringWriter();
        PrintWriter mPrintWriter = new PrintWriter(mStringWriter);
        e.printStackTrace(mPrintWriter);
        String crashContent = mStringWriter.toString();
        //可以封装成文件创上传服务器或者先保存在sdcard.我这里是跳转到一个界面,在手机端显示错误信息。
        Intent mIntent = new Intent(mContext, BugReportActivity.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mIntent.putExtra(BugReportActivity.CRASH_CONTENT, crashContent);
        mContext.startActivity(mIntent);
        System.exit(0);
    }
}
public class BugReportActivity extends Activity {

    public static final String CRASH_CONTENT = "crash";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bug_report);
        TextView mCrash = (TextView) findViewById(R.id.tv_show_crash_message);
        String message = getIntent().getStringExtra(CRASH_CONTENT);
        mCrash.setMovementMethod(ScrollingMovementMethod.getInstance());
        mCrash.append(message);
    }
}

public class AlgorithmApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandle(this));
    }
}

不要忘记在manifest添加:BugReportActivity




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值