資源描述:
《AndroidJSON解析示例代碼》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、AndroidJSON解析示例代碼??--未審核編輯文檔?來自google官方的有關(guān)Android平臺的JSON解析示例,如果遠程服務(wù)器使用了json而不是xml的數(shù)據(jù)提供,在Android平臺上已經(jīng)內(nèi)置的org.json包可以很方便的實現(xiàn)手機客戶端的解析處理。下面Android123一起分析下這個例子,幫助Android開發(fā)者需要有關(guān)HTTP通訊、正則表達式、JSON解析、appWidget開發(fā)的一些知識。publicclassWordWidgetextendsAppWidgetProvider{//app
2、Widget???@Override???publicvoidonUpdate(Contextcontext,AppWidgetManagerappWidgetManager,???????????int[]appWidgetIds){????????context.startService(newIntent(context,UpdateService.class));//避免ANR,所以Widget中開了個服務(wù)???}???publicstaticclassUpdateServiceextendsServ
3、ice{???????@Override???????publicvoidonStart(Intentintent,intstartId){???????????//Buildthewidgetupdatefortoday???????????RemoteViewsupdateViews=buildUpdate(this);???????????ComponentNamethisWidget=newComponentName(this,WordWidget.class);???????????AppWidge
4、tManagermanager=AppWidgetManager.getInstance(this);???????????manager.updateAppWidget(thisWidget,updateViews);???????}???????publicRemoteViewsbuildUpdate(Contextcontext){???????????//Pickoutmonthnamesfromresources???????????Resourcesres=context.getResources
5、();???????????String[]monthNames=res.getStringArray(R.array.month_names);????????????Timetoday=newTime();???????????today.setToNow();???????????StringpageName=res.getString(R.string.template_wotd_title,???????????????????monthNames[today.month],today.monthD
6、ay);???????????RemoteViewsupdateViews=null;???????????StringpageContent="";???????????try{????????????????SimpleWikiHelper.prepareUserAgent(context);???????????????pageContent=SimpleWikiHelper.getPageContent(pageName,false);???????????}catch(ApiExceptione){
7、???????????????Log.e("WordWidget","Couldn'tcontactAPI",e);???????????}catch(ParseExceptione){???????????????Log.e("WordWidget","Couldn'tparseAPIresponse",e);???????????}???????????Patternpattern=Pattern.compile(SimpleWikiHelper.WORD_OF_DAY_REGEX);//正則表達式處理,
8、有關(guān)定義見下面的SimpleWikiHelper類???????????Matchermatcher=pattern.matcher(pageContent);???????????if(matcher.find()){????????????????updateViews=newRemoteViews(context.getPackageName(),R.layout.widget_word);?