Android实现捕获未知异常并提交给服务器的方法
本文实例讲述了Android实现捕获未知异常并提交给服务器的方法。分享给大家供大家参考,具体如下:
在Android应用中,即便应用已经投放市场,但有时也会遇到一些未知的异常,此时如果能够获得用户的反馈信息,那么对于我们应用的开发是一个很好的帮助
为了实现这样的效果,我们需要做如下工作
写一个类实现UncaughtExceptionHandler接口,重写uncaughtException方法
功能描述:当应用出现了未知异常,应用强制退出,应用再次启动时,提示用户是否将错误信息反馈给开发者
publicclassMyUncaughtExceptionHandlerimplementsUncaughtExceptionHandler{ privatestaticfinalStringTAG="MyUncaughtExceptionHandler"; //将错误信息保存到sharepreference中 privatestaticSharedPreferencesbugPreferences; privatestaticSharedPreferences.EditorbugEditor; privatestaticContextmContext; privatestaticPackageInfopackageInfo; privateUncaughtExceptionHandlerdefaultUncaughtExceptionHandler; privatestaticHandleProgressDialogprogressDialog; //保存错误原因的字段 privatestaticStringbugExistStr=""; privatestaticHandlerhandler=newHandler(){ @Override publicvoidhandleMessage(Messagemsg){ progressDialog.dismiss(); } }; publicMyUncaughtExceptionHandler(Contextcontext){ try{ mContext=context; packageInfo=context.getPackageManager().getPackageInfo( context.getPackageName(),0); bugPreferences=context.getSharedPreferences("bug",0); bugEditor=bugPreferences.edit(); defaultUncaughtExceptionHandler=Thread .getDefaultUncaughtExceptionHandler(); }catch(NameNotFoundExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); } } //当异常发生时,会调用这个方法 publicvoiduncaughtException(Threadth,Throwablet){ try{ //保存bug saveBugText(t); defaultUncaughtExceptionHandler.uncaughtException(th,t); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); } } privatevoidsaveBugText(Throwableex)throwsFileNotFoundException{ Writerwriter=newStringWriter(); PrintWriterprintWriter=newPrintWriter(writer); ex.printStackTrace(printWriter); Throwablecause=ex.getCause(); while(cause!=null){ cause.printStackTrace(printWriter); cause=cause.getCause(); } printWriter.close(); bugEditor.putString("bugText",writer.toString()); bugEditor.commit(); } //下次开启应用的时候,如果上次产生了未知异常则显示对话框应用与用户反馈 publicstaticvoidshowBugReportDialog(finalContextcontext){ bugExistStr=context.getSharedPreferences("bug",0).getString( "bugText",""); if(bugExistStr!=null&&!bugExistStr.equals("")){ AlertDialog.Builderbuilder=newAlertDialog.Builder(context); builder.setTitle(R.string.bug_report); builder.setMessage(R.string.whether_report_to_developer); builder.setNegativeButton(R.string.cancel,newOnClickListener(){ publicvoidonClick(DialogInterfacedialog,intwhich){ finish(dialog); } }); builder.setPositiveButton(R.string.send,newOnClickListener(){ publicvoidonClick(DialogInterfacedialog,intwhich){ //提交bug到服务器 postBugReportInBackground(context); dialog.dismiss(); } }); AlertDialogdialog=builder.create(); dialog.show(); } } privatestaticvoidpostBugReportInBackground(finalContextcontext){ progressDialog=newHandleProgressDialog(context); progressDialog.show(); newThread(newRunnable(){ publicvoidrun(){ postBugReport(); //将之前的bug信息清除掉 if(bugExistStr!=null){ bugEditor.putString("bugText",""); bugEditor.commit(); } handler.sendEmptyMessage(0); } }).start(); } /** *SendBugReport. */ privatestaticvoidpostBugReport(){ List<NameValuePair>nvps=newArrayList<NameValuePair>(); nvps.add(newBasicNameValuePair("device",Build.DEVICE)); nvps.add(newBasicNameValuePair("model",Build.MODEL)); nvps.add(newBasicNameValuePair("sdk-version",Build.VERSION.SDK)); nvps.add(newBasicNameValuePair("apk-version",packageInfo.versionName)); nvps.add(newBasicNameValuePair("bug",bugExistStr)); try{ HttpPosthttpPost=newHttpPost(Constants.BaseUrl +"c=main&a=androidCrash"); httpPost.setEntity(newUrlEncodedFormEntity(nvps,HTTP.UTF_8)); DefaultHttpClienthttpClient=newDefaultHttpClient(); HttpParamsparams=httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params,5000); HttpConnectionParams.setSoTimeout(params,5000); httpClient.execute(httpPost); }catch(IOExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); } } privatestaticvoidfinish(DialogInterfacedialog){ if(bugExistStr!=null){ bugEditor.putString("bugText",""); bugEditor.commit(); } dialog.dismiss(); } }
在需要捕捉异常的地方调用
@Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); appApplication=(APPApplication)getApplication(); appApplication.activites.add(this); initViews(); Thread.setDefaultUncaughtExceptionHandler(newMyUncaughtExceptionHandler( MainActivity.this)); MyUncaughtExceptionHandler.showBugReportDialog(this); }
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android操作SQLite数据库技巧总结》、《Android操作json格式数据技巧总结》、《Android数据库操作技巧总结》、《Android文件操作技巧汇总》、《Android编程开发之SD卡操作方法汇总》、《Android资源操作技巧汇总》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。