现在的位置: 首页 > 综合 > 正文

‍‍android捕获全局异常,并对异常做出处理

2013年05月06日 ⁄ 综合 ⁄ 共 1379字 ⁄ 字号 评论关闭

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

具体的实方法如下:

利用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

抱歉!评论已关闭.