源码介绍本项目是一个简单的全局异常捕获示例。捕捉到异常后,可以将异常信息写入文件,以供后续分析或在退出程序前以友好的方式提示。源码源码运行截图:publinClassuncughaughtexceptionImplementsuncaughtexceptionHandler{privateFinalStaticStringTag=“uncaughtexception”;privaughateSuncaugheStaticeStaticEncaughtaticEncaughtaticeStaticEncaughteStaticeStaticeStaticeStaticEncoughTemaughtexception;,string="">infos=newHashMap();publicContextgetContext(){returncontext;}publicvoidsetContext(Contextcontext){this.context=context;}privateUncaughtException(){//TODOAuto-generatedconstructorstub}/***单例多线程环境下避免异常的同步方法**@return*/publicsynchronizedstaticUncaughtExceptiongetInstance(){if(mUncaughtException==null){mUncaughtException=newUncaughtException();}returnmUncaughtException;}/***初始化,把当前对象设置为UncaughtExceptionHandler处理器*/publicvoidinit(){Thread.setDefaultUncaughtExceptionHandler(mUncaughtException);}@OverridepublicvoiduncaughtException(Threadthread,Throwableex){//TODOAuto-生成方法tub//处理异常,我们也可以将异常信息写入文件,方便后续分析saveCrashInfo2File(ex);Log.e(TAG,"uncaughtExceptionthread:"+thread+"||name="+thread.getName()+"||id="+thread.getId()+"||exception="+ex);/*Looper.prepare();Toast.makeText(context,"程序异常,立即退出",1).show();System.exit(0);Looper.loop();*/showDialog();}privatevoidshowDialog(){newThread(){@Overridepublicvoidrun(){Looper.prepare();newAlertDialog.Builder(context).setTitle("眼泪提示").setCancelable(false).setMessage("师傅,我有崩溃了。..").setNeutralButton("我知道",newOnClickListener(){@OverridepublicvoidonClick(DialogInterfacedialog,intwhich){System.exit(0);}}).create().show();Looper.loop();}}.start();}/***保存错误信息到文件**@paramex*@return返回文件名,方便将文件传到服务器*/privateStringsaveCrashInfo2File(Throwableex){StringBuffersb=newStringBuffer();longtimestamp=System.currentTimeMillis();Stringtime=formatter.format(newDate());sb.append("\n"+time+"----");for(Map.Entryentry:infos.entrySet()){Stringkey=entry.getKey();Stringvalue=entry.getValue();sb.append(key+"="+value+"\n");}Writerwriter=newStringWriter();PrintWriterprintWriter=newPrintWriter(writer);ex.printStackTrace(printWriter);Throwablecause=ex.getCause();while(cause!=null){cause.printStackTrace(printWriter);cause=cause.getCause();}printWriter.close();Stringresult=writer.toString();sb.append(result);try{StringfileName="exception.log";if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){Stringpath="/sdcard/crash/";Filedir=newFile(path);if(!dir.exists()){dir.mkdirs();}FileOutputStreamfos=newFileOutputStream(path+fileName,true);fos.write(sb.toString().getBytes());fos.close();}returnfileName;}catch(Exceptione){Log.e(TAG,"anerroroccuredwhilewritingfile...",e);}returnnull;}}源码链接:http://down.51cto.com/data/1980812