来自Google官方的有关Android平台的JSON解析示例,如果远程服务器使用了json而不是xml的数据提供,在Android平台上已经内置的org.json包可以很方便的实现手机客户端的解析处理。下面Android123一起分析下这个例子,帮助Android开发者需要有关HTTP通讯、正则表达式、JSON解析、appWidget开发的一些知识。

publicclassWordWidgetextendsAppWidgetProvider{//appWidget

@Override

publicvoidonUpdate(Contextcontext,AppWidgetManagerappWidgetManager,

int[]appWidgetIds){

context.startService(newIntent(context,UpdateService.class));//避免ANR,所以Widget中开了个服务

}

publicstaticclassUpdateServiceextendsService{

@Override

publicvoidonStart(Intentintent,intstartId){

//Buildthewidgetupdatefortoday

RemoteViewsupdateViews=buildUpdate(this);

ComponentNamethisWidget=newComponentName(this,WordWidget.class);

AppWidgetManagermanager=AppWidgetManager.getInstance(this);

manager.updateAppWidget(thisWidget,updateViews);

}

publicRemoteViewsbuildUpdate(Contextcontext){

//Pickoutmonthnamesfromresources

Resourcesres=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;

}

@Override

publicIBinderonBind(Intentintent){

//Wedon'tneedtobindtothisservice

returnnull;

}

}

}

有关网络通讯的实体类,以及一些常量定义如下:

publicclassSimpleWikiHelper{

privatestaticfinalStringTAG="SimpleWikiHelper";

publicstaticfinalStringWORD_OF_DAY_REGEX=

"(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}";

privatestaticfinalStringWIKTIONARY_PAGE=

"http://en.wiktionary.org/w/api.php?action=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{

//Readpackagenameandversionnumberfrommanifest

PackageManagermanager=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());

}

HttpEntityentity=response.getEntity();

InputStreaminputStream=entity.getContent();//获取HTTP返回的数据流

ByteArrayOutputStreamcontent=newByteArrayOutputStream();

intreadBytes=0;

while((readBytes=inputStream.read(sBuffer))!=-1){

content.write(sBuffer,0,readBytes);//转化为字节数组流

}

returnnewString(content.toByteArray());//从字节数组构建String

}catch(IOExceptione){

thrownewApiException("ProblemcommunicatingwithAPI",e);

}

}

}

有关整个每日维基的widget例子比较简单,主要是帮助大家积累常用代码,了解Android平台JSON的处理方式,毕竟很多Server还是Java的。

http://www.android123.com.cn/androidkaifa/664.html