zoukankan      html  css  js  c++  java
  • 安卓学习34

    今天学习了安卓的一些知识其中主要的是:

    Android JSON解析示例代码

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

    [java]view plaincopyprint?

    1. public class WordWidget extends AppWidgetProvider { //appWidget

    2. @Override

    3. public void onUpdate(Context context, AppWidgetManager appWidg

    etManager,

     int[] appWidgetIds) {

    5. context.startService(new Intent(context, UpdateService.class)); //

    避免ANR,所以Widget中开了个服务

    6. } public static class UpdateService extends Service {

    7. @Override

    8. public void onStart(Intent intent, int startId) {

    9. // Build the widget update for today

    10. RemoteViews updateViews = buildUpdate(this); Compo

    nentName thisWidget = new ComponentName(this, WordWidget.class );

    11. AppWidgetManager manager = AppWidgetManager.getInstanc

    e(this);

    12. manager.updateAppWidget(thisWidget, updateViews);

    13. } public RemoteViews buildUpdate(Context context) {

    14. // Pick out month names from resources

    15. Resources res = context.getResources();

    16. String[] monthNames = res.getStringArray(R.array.month_nam

    es); Time today = new Time();

    17. today.setToNow(); String pageName = res.getString(R.s

    tring.template_wotd_title,

    18. monthNames[today.month], today.monthDay);

    19. RemoteViews updateViews = null;

    20. String pageContent = ""; try {

    21. SimpleWikiHelper.prepareUserAgent(context);

    22. pageContent = SimpleWikiHelper.getPageContent(pageNam

    e, false);

    23. } catch (ApiException e) {

    24. Log.e("WordWidget", "Couldn't contact API", e);

    25. } catch (ParseException e) {

    26. Log.e("WordWidget", "Couldn't parse API response", e);

    27. } Pattern pattern = http://www.doczj.com/doc/ca10c5fc6037ee06eff9aef8941ea76e58fa4a08.htmlpile(SimpleWikiHelper.W

    ORD_OF_DAY_REGEX); //正则表达式处理,有关定义见下面的

    SimpleWikiHelper类

    28. Matcher matcher = pattern.matcher(pageContent);

    29. if (matcher.find()) {

    30. updateViews = new RemoteViews(context.getPackageName

    (), http://www.doczj.com/doc/ca10c5fc6037ee06eff9aef8941ea76e58fa4a08.htmlyout.widget_word); String wordTitle = matcher.group(

    1);

    31. updateViews.setTextViewText(R.id.word_title, wordTitle);

    32. updateViews.setTextViewText(R.id.word_type, matcher.grou

    p(2));

    33. updateViews.setTextViewText(R.id.definition, matcher.group

    (3).trim()); String definePage = res.getString(R.string.templat

    e_define_url,

    34. Uri.encode(wordTitle));

    35. Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri.pa

    rse(definePage)); //这里是打开相应的网页,所以Uri是http的url,action 是view即打开web浏览器

    36. PendingIntent pendingIntent = PendingIntent.getActivity(cont

    ext,

    37. 0 /* no requestCode */, defineIntent, 0 /* no flags */);

    38. updateViews.setOnClickPendingIntent(R.id.widget, pendingI

    ntent); //单击Widget打开Activity } else {

    39. updateViews = new RemoteViews(context.getPackageName

    (), http://www.doczj.com/doc/ca10c5fc6037ee06eff9aef8941ea76e58fa4a08.htmlyout.widget_message);

    40. CharSequence errorMessage = context.getText(R.string.wid

    get_error);

    41. updateViews.setTextViewText(R.id.message, errorMessage)

    ;

    42. }

    43. return updateViews;

    44. } @Override

    45. public IBinder onBind(Intent intent) {

    46. // We don't need to bind to this service

    47. return null;

    48. }

    49. }

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

    下: public class SimpleWikiHelper {

    51. private static final String TAG = "SimpleWikiHelper"; public static fi

    nal String WORD_OF_DAY_REGEX =

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

    al String WIKTIONARY_PAGE =

    53. "http://www.doczj.com/doc/ca10c5fc6037ee06eff9aef8941ea76e58fa4a08.html/w/api.php?action=query&prop=revision

    s&titles=%s&" +

    54. "rvprop=content&format=json%s"; private static final String

    WIKTIONARY_EXPAND_TEMPLATES =

    55. "&rvexpandtemplates=true"; private static final int HTTP_ST

    ATUS_OK = 200; private static byte[] sBuffer = new byte[512]; pri vate static String sUserAgent = null; public static class ApiExceptio n extends Exception {

    56. public ApiException(String detailMessage, Throwable throwable) {

    57. super(detailMessage, throwable);

    58. } public ApiException(String detailMessage) {

    59. super(detailMessage);

    60. }

    61. } public static class ParseException extends Exception {

    62. public ParseException(String detailMessage, Throwable throwabl

    e) {

    63. super(detailMessage, throwable);

    64. }

    65. } public static void prepareUserAgent(Context context) {

    66. try {

    67. // Read package name and version number from manifest

    68. PackageManager manager = context.getPackageManager();

    69. PackageInfo info = manager.getPackageInfo(context.getPacka

    geName(), 0);

    70. sUserAgent = String.format(context.getString(R.string.template

    _user_agent),

    71. info.packageName, info.versionName); } catch(Name

    NotFoundException e) {

    72. Log.e(TAG, "Couldn't find package information in PackageMan

    ager", e);

    73. }

    74. } public static String getPageContent(String title, boolean expandT

    emplates)

    75. throws ApiException, ParseException {

    76. String encodedTitle = Uri.encode(title);

    77. String expandClause = expandTemplates ? WIKTIONARY_EXPA

    ND_TEMPLATES : ""; String content = getUrlContent(String.form at(WIKTIONARY_PAGE, encodedTitle, expandClause));

    78. try {

    79. JSONObject response = new JSONObject(content);

    80. JSONObject query = response.getJSONObject("query");

    81. JSONObject pages = query.getJSONObject("pages");

    82. JSONObject page = pages.getJSONObject((String) pages.keys

    ().next());

    83. JSONArray revisions = page.getJSONArray("revisions");

    84. JSONObject revision = revisions.getJSONObject(0);

    85. return revision.getString("*");

    86. } catch (JSONException e) {

    87. throw new ParseException("Problem parsing API response", e);

    88. }

    89. } protected static synchronized String getUrlContent(String url) thr

    ows ApiException {

    90. if (sUserAgent == null) {

    91. throw new ApiException("User-Agent string must be prepared")

    ;

    92. } HttpClient client = new DefaultHttpClient();

    93. HttpGet request = new HttpGet(url);

    94. request.setHeader("User-Agent", sUserAgent); //设置客户端标

    识 try {

    95. HttpResponse response = client.execute(request); Statu

    sLine status = response.getStatusLine();

    96. if (status.getStatusCode() != HTTP_STATUS_OK) {

    97. throw new ApiException("Invalid response from server: " +

    98. status.toString());

    99. } HttpEntity entity = response.getEntity();

    100. InputStream inputStream = entity.getContent(); //获取

    HTTP返回的数据

    流 ByteArrayOutputStream content = new ByteArrayOutputStre

    am(); int readBytes = 0;

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

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

    103. } return new String(content.toByteArray()); //从字节数组构建String

    104. } catch (IOException e) {

    105. throw new ApiException("Problem communicating with API ", e);

    106. }

    107. }

    108. }

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

  • 相关阅读:
    Why Are Some OSPF Routes in the Database but Not in the Routing Table?
    (OK) 手动 添加 删除 bridge tap — tunctl — brctl
    (OK) kvm虚拟机克隆—KVM本机虚拟机直接克隆—通过复制xml文件与磁盘文件复制克隆
    KVM虚拟化管理
    (OK) init_install_android-x86_64_in_QEMU-KVM.sh
    (OK) init_in_android-x86_64.sh
    (OK)(OK) using adb with KVM (qemu)
    (OK)(OK) QEMU-KVM —— HOST AND GUEST can ping each other
    Example Sharing Host files with the Guest — 9p — qemu-kvm
    (OK) 图解几个与Linux网络虚拟化相关的虚拟网卡-VETH/MACVLAN/MACVTAP/IPVLAN
  • 原文地址:https://www.cnblogs.com/092e/p/14916656.html
Copyright © 2011-2022 走看看