碰到程序崩溃时,闪退效果,不会提示"xxx程序异常,退出程序"。这样的效果就要使用到未捕获异常来实现,这里记录了我的一个写法。其实原理很简单,设置程序的未捕获异常监听,实现监听的一个方法,在该方法中现实直接没有提示的退出程序。


捕获异常工具类

packagecom.tdh.http;importjava.io.PrintWriter;importjava.io.StringWriter;importjava.lang.Thread.UncaughtExceptionHandler;importandroid.content.Context;importandroid.util.Log;publicclassOtherExceptionsHandlerimplementsUncaughtExceptionHandler{privatestaticContextmAppContext;//上下文对象privatestaticOtherExceptionsHandlerinstance;//单例引用,这里我们做成单例的,因为我们一个应用程序里面只需要一个UncaughtExceptionHandler实例privateOtherExceptionsHandler(){}publicsynchronizedstaticOtherExceptionsHandlergetInstance(){//同步方法,以免单例多线程环境下出现异常if(instance==null){instance=newOtherExceptionsHandler();}returninstance;}/**需要上下文对象的初始化*/publicsynchronizedOtherExceptionsHandlerinit(Contextcontext){//初始化,把当前对象设置成UncaughtExceptionHandler处理器Thread.setDefaultUncaughtExceptionHandler(this);mAppContext=context.getApplicationContext();returninstance;}publicsynchronizedOtherExceptionsHandlerinit(){//初始化,把当前对象设置成UncaughtExceptionHandler处理器Thread.setDefaultUncaughtExceptionHandler(this);returninstance;}@OverridepublicvoiduncaughtException(Threadthread,Throwableex){if(mAppContext!=null){otherException(thread,ex,mAppContext);}otherException(thread,ex);}/***处理异常的一般情况*@paramthread*@paramex*/publicvoidotherException(Threadthread,Throwableex){StringWritersw=newStringWriter();ex.printStackTrace(newPrintWriter(sw,true));Log.e("uncaughtException","thread:"+thread+"name:"+thread.getName()+"id:"+thread.getId()+"exception:"+Log.getStackTraceString(ex));System.exit(0);}/***处理异常的特殊情况,一般是需要用到上下文对象context*@paramthread*@paramex*@paramcontext*/publicvoidotherException(Threadthread,Throwableex,Contextcontext){}}


2.在Application中初始化

packagecom.tdh.http;importandroid.app.Application;publicclassMyApplicationextendsApplication{@OverridepublicvoidonCreate(){super.onCreate();OtherExceptionsHandler.getInstance().init();}}


3.在AndroidManifest.xml中配置

<applicationandroid:name="com.tdh.http.MyApplication"...>


4.在activity中测试

findViewById(R.id.button1).setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewv){Stringe=null;e.getBytes();}});