全局捕获异常

activity 页面 自己写一个异常

  CrashHandler.getInstance().init(this); 
  String a=null;String 
  b=a.toString();
  Log.i("xxx",b);

自定义类 CrashHandler 捕获到弹框及打印到SD 下

  public class CrashHandler implements Thread.UncaughtExceptionHandler {

     private int num=1;
     private Context mContext;
     private Thread.UncaughtExceptionHandler mDefaultHanlder;
     private static CrashHandler crashHandler=new CrashHandler();

     //饿汉
    private CrashHandler(){

    }
    public static CrashHandler getInstance(){
        return crashHandler;
    }

    public void init(Context context){
        mContext=context;
        mDefaultHanlder=Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    @Override
    public void uncaughtException(Thread t, final Throwable e) {
        Log.i("xxx",e.toString());

        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                new AlertDialog.Builder(mContext).setTitle("提示").setMessage("程序崩溃了").setNeutralButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        File file=new File("/mnt/sdcard/Android/data/crach.txt");
                        if (!file.exists()){
                            try {
                                file.createNewFile();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                        byte[] bytes = new byte[512];
                        bytes=e.toString().getBytes();
                        int b=bytes.length;
                        FileOutputStream fos=null;
                        try {
                            fos=new FileOutputStream(file);
                            fos.write(bytes,0,b);
                            fos.write(bytes);
                            fos.close();
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        System.exit(0);
                    }
                }).create().show();
                Looper.loop();

            }
        }.start();

    }
}      

清单文件写的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值