zoukankan      html  css  js  c++  java
  • android捕获全局异常,并对异常做出处理

    在做项目时,经常会把错误利用异常抛出去,这样在开发时就可以通过手机抛的异常排查错误,很方便。但是当程序开发完毕,版本稳定,需要上线时,为了避免抛出异常影响用户感受,可以捕获全局异常,对异常做出处理。

    具体的实方法如下:

    利用Thread.UncaughtExceptionHandler 获取异常,并对异常做出处理:

    public class MyUncaughtExceptionHandler implements 
            Thread.UncaughtExceptionHandler { 
        private Thread.UncaughtExceptionHandler a; 
        MyUncaughtExceptionHandler(){ 
             this.a = Thread.getDefaultUncaughtExceptionHandler(); 
        } 
        @Override 
        public void uncaughtException(Thread thread, Throwable ex) { 
            Log.i("huilurry","ppppppppppppp="+ex.getMessage()); 
        //是否抛出异常 
    //        if(a!=null) 
    //        a.uncaughtException(thread, ex); 
        } 
    }

    具体调用:

    public class HuiLurryActivty extends Activity { 
        @Override 
        public void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.main); 
            String t=android.provider.Settings.System.getString(getContentResolver(), "android_id"); 
            Log.i("huilurry","android_id="+t); 
            huilurry(); 
            throw new NullPointerException("is null"); 
        } 
        HandlerThread localHandlerThread; 
        Handler handler; 
        private void huilurry() 
        { 
           localHandlerThread=new HandlerThread("huilurry"); 
            localHandlerThread.start(); 
            handler=new Handler(localHandlerThread.getLooper()); 
            Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler()); 
        } 
    }

    主要是利用了Hander和HandlerThread。

    源代码见:http://wangjun-memory.googlecode.com/svn/trunk/android.huilurry

  • 相关阅读:
    Git标签使用技巧
    Git入门基本概述
    过滤器+缓存在.NET5WebApi项目中的简单使用
    在.NET5中 使用JWT鉴权授权
    Git常用开发命令
    时间戳的实际使用
    两个日期字段相减,进行计算
    MQ的理论理解
    第一周学习C语言的总结!
    问题(the question)
  • 原文地址:https://www.cnblogs.com/xyzlmn/p/3168212.html
Copyright © 2011-2022 走看看