您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 其它行业文档 > android 重要知识点
Android开发网上的一些重要知识点[2]博客分类:Android11.AndroidJSON解析示例代码来自Google官方的有关Android平台的JSON解析示例,如果远程服务器使用了json而不是xml的数据提供,在Android平台上已经内置的org.json包可以很方便的实现手机客户端的解析处理。下面Android123一起分析下这个例子,帮助Android开发者需要有关HTTP通讯、正则表达式、JSON解析、appWidget开发的一些知识。publicclassWordWidgetextendsAppWidgetProvider{//appWidget@OverridepublicvoidonUpdate(Contextcontext,AppWidgetManagerappWidgetManager,int[]appWidgetIds){context.startService(newIntent(context,UpdateService.class));//避免ANR,所以Widget中开了个服务}publicstaticclassUpdateServiceextendsService{@OverridepublicvoidonStart(Intentintent,intstartId){//BuildthewidgetupdatefortodayRemoteViewsupdateViews=buildUpdate(this);ComponentNamethisWidget=newComponentName(this,WordWidget.class);AppWidgetManagermanager=AppWidgetManager.getInstance(this);manager.updateAppWidget(thisWidget,updateViews);}publicRemoteViewsbuildUpdate(Contextcontext){//PickoutmonthnamesfromresourcesResourcesres=context.getResources();String[]monthNames=res.getStringArray(R.array.month_names);Timetoday=newTime();today.setToNow();StringpageName=res.getString(R.string.template_wotd_title,monthNames[today.month],today.monthDay);RemoteViewsupdateViews=null;StringpageContent=;try{SimpleWikiHelper.prepareUserAgent(context);pageContent=SimpleWikiHelper.getPageContent(pageName,false);}catch(ApiExceptione){Log.e(WordWidget,Couldn'tcontactAPI,e);}catch(ParseExceptione){Log.e(WordWidget,Couldn'tparseAPIresponse,e);}Patternpattern=Pattern.compile(SimpleWikiHelper.WORD_OF_DAY_REGEX);//正则表达式处理,有关定义见下面的SimpleWikiHelper类Matchermatcher=pattern.matcher(pageContent);if(matcher.find()){updateViews=newRemoteViews(context.getPackageName(),R.layout.widget_word);StringwordTitle=matcher.group(1);updateViews.setTextViewText(R.id.word_title,wordTitle);updateViews.setTextViewText(R.id.word_type,matcher.group(2));updateViews.setTextViewText(R.id.definition,matcher.group(3).trim());StringdefinePage=res.getString(R.string.template_define_url,Uri.encode(wordTitle));IntentdefineIntent=newIntent(Intent.ACTION_VIEW,Uri.parse(definePage));//这里是打开相应的网页,所以Uri是http的url,action是view即打开web浏览器PendingIntentpendingIntent=PendingIntent.getActivity(context,0/*norequestCode*/,defineIntent,0/*noflags*/);updateViews.setOnClickPendingIntent(R.id.widget,pendingIntent);//单击Widget打开Activity}else{updateViews=newRemoteViews(context.getPackageName(),R.layout.widget_message);CharSequenceerrorMessage=context.getText(R.string.widget_error);updateViews.setTextViewText(R.id.message,errorMessage);}returnupdateViews;}@OverridepublicIBinderonBind(Intentintent){//Wedon'tneedtobindtothisservicereturnnull;}}}有关网络通讯的实体类,以及一些常量定义如下:publicclassSimpleWikiHelper{privatestaticfinalStringTAG=SimpleWikiHelper;publicstaticfinalStringWORD_OF_DAY_REGEX=(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\};privatestaticfinalStringWIKTIONARY_PAGE==query&prop=revisions&titles=%s&+rvprop=content&format=json%s;privatestaticfinalStringWIKTIONARY_EXPAND_TEMPLATES=&rvexpandtemplates=true;privatestaticfinalintHTTP_STATUS_OK=200;privatestaticbyte[]sBuffer=newbyte[512];privatestaticStringsUserAgent=null;publicstaticclassApiExceptionextendsException{publicApiException(StringdetailMessage,Throwablethrowable){super(detailMessage,throwable);}publicApiException(StringdetailMessage){super(detailMessage);}}publicstaticclassParseExceptionextendsException{publicParseException(StringdetailMessage,Throwablethrowable){super(detailMessage,throwable);}}publicstaticvoidprepareUserAgent(Contextcontext){try{//ReadpackagenameandversionnumberfrommanifestPackageManagermanager=context.getPackageManager();PackageInfoinfo=manager.getPackageInfo(context.getPackageName(),0);sUserAgent=String.format(context.getString(R.string.template_user_agent),info.packageName,info.versionName);}catch(NameNotFoundExceptione){Log.e(TAG,Couldn'tfindpackageinformationinPackageManager,e);}}publicstaticStringgetPageContent(Stringtitle,booleanexpandTemplates)throwsApiException,ParseException{StringencodedTitle=Uri.encode(title);StringexpandClause=expandTemplates?WIKTIONARY_EXPAND_TEMPLATES:;Stringcontent=getUrlContent(String.format(WIKTIONARY_PAGE,encodedTitle,expandClause));try{JSONObjectresponse=newJSONObject(content);JSONObjectquery=response.getJSONObject(query);JSONObjectpages=query.getJSONObject(pages);JSONObjectpage=pages.getJSONObject((String)pages.keys().next());JSONArrayrevisions=page.getJSONArray(revisions);JSONObjectrevision=revisions.getJSONObject(0);returnrevision.getString(*);}catch(JSONExceptione){thrownewParseException(ProblemparsingAPIresponse,e);}}protectedstaticsynchronizedStringgetUrlContent(Stringurl)throwsApiException{if(sUserAgent==null){thrownewApiException(User-Agentstringmustbeprepared);}HttpClientclient=newDefaultHttpClient();HttpGetrequest=newHttpGet(url);request.setHeader(User-Agent,sUserAgent);//设置客户端标识try{HttpResponseresponse=client.execute(request);StatusLinestatus=response.getStatusLine();if(status.getStatusCode()!=HTTP_STATUS_OK){thrownewApiException(Invalidresponsefromserver:+status.toString());
本文标题:android 重要知识点
链接地址:https://www.777doc.com/doc-4890660 .html