Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android JSON 解析實例:打造每日一词 Widget

編輯:進階開發

如果後端服務提供的是 JSON 而非 XML,Android 端不必額外引入任何套件——org.json 早已內建。這裡以 Google 官方的「每日一詞」Widget 範例為例,一次涵蓋 HTTP 通訊、正則表達式、JSON 解析與 AppWidget 開發。

Widget 端:AppWidgetProvider

public class WordWidget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        // 開 Service 避免 ANR
        context.startService(new Intent(context, UpdateService.class));
    }

    public static class UpdateService extends Service {

        @Override
        public void onStart(Intent intent, int startId) {
            RemoteViews updateViews = buildUpdate(this);

            ComponentName thisWidget = new ComponentName(this, WordWidget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, updateViews);
        }

        public RemoteViews buildUpdate(Context context) {
            Resources res = context.getResources();
            String[] monthNames = res.getStringArray(R.array.month_names);

            Time today = new Time();
            today.setToNow();

            String pageName = res.getString(R.string.template_wotd_title,
                    monthNames[today.month], today.monthDay);

            RemoteViews updateViews = null;
            String pageContent = "";

            try {
                SimpleWikiHelper.prepareUserAgent(context);
                pageContent = SimpleWikiHelper.getPageContent(pageName, false);
            } catch (ApiException e) {
                Log.e("WordWidget", "Couldn't contact API", e);
            } catch (ParseException e) {
                Log.e("WordWidget", "Couldn't parse API response", e);
            }

            // 用正則表達式從頁面內容中擷取需要的欄位
            Pattern pattern = Pattern.compile(SimpleWikiHelper.WORD_OF_DAY_REGEX);
            Matcher matcher = pattern.matcher(pageContent);

            if (matcher.find()) {
                updateViews = new RemoteViews(
                        context.getPackageName(), R.layout.widget_word);

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

                // 點擊 Widget 開啟瀏覽器看定義頁
                String definePage = res.getString(R.string.template_define_url,
                        Uri.encode(wordTitle));
                Intent defineIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(definePage));
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        context, 0, defineIntent, 0);
                updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent);
            } else {
                // 抓不到資料就顯示錯誤訊息
                updateViews = new RemoteViews(
                        context.getPackageName(), R.layout.widget_message);
                updateViews.setTextViewText(R.id.message,
                        context.getText(R.string.widget_error));
            }
            return updateViews;
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
}

網路與解析層

public class SimpleWikiHelper {
    private static final String TAG = "SimpleWikiHelper";

    public static final String WORD_OF_DAY_REGEX =
            "(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}";

    private static final String WIKTIONARY_PAGE =
        "https://en.wiktionary.org/w/api.php?action=query&prop=revisions"
        + "&titles=%s&rvprop=content&format=json%s";

    private static final String WIKTIONARY_EXPAND_TEMPLATES =
            "&rvexpandtemplates=true";

    private static final int HTTP_STATUS_OK = 200;
    private static byte[] sBuffer = new byte[512];
    private static String sUserAgent = null;

    public static class ApiException extends Exception { ... }
    public static class ParseException extends Exception { ... }

    public static void prepareUserAgent(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(
                    context.getPackageName(), 0);
            sUserAgent = String.format(
                    context.getString(R.string.template_user_agent),
                    info.packageName, info.versionName);
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Couldn't find package information in PackageManager", e);
        }
    }
}

JSON 解析本體

這是全例的核心,五層巢狀物件逐層剝開:

public static String getPageContent(String title, boolean expandTemplates)
        throws ApiException, ParseException {

    String encodedTitle = Uri.encode(title);
    String expandClause = expandTemplates ? WIKTIONARY_EXPAND_TEMPLATES : "";

    String content = getUrlContent(
            String.format(WIKTIONARY_PAGE, encodedTitle, expandClause));
    try {
        JSONObject response = new JSONObject(content);
        JSONObject query    = response.getJSONObject("query");
        JSONObject pages    = query.getJSONObject("pages");
        // pages 的 key 是頁 id,我們只有一頁,直接取第一個
        JSONObject page     = pages.getJSONObject((String) pages.keys().next());
        JSONArray  revisions = page.getJSONArray("revisions");
        JSONObject revision  = revisions.getJSONObject(0);
        return revision.getString("*");   // 維基的內容放在 "*" 這個欄位
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response", e);
    }
}

HTTP 取資料

protected static synchronized String getUrlContent(String url)
        throws ApiException {
    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    request.setHeader("User-Agent", sUserAgent);   // 有些服務會擋空 UA

    try {
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            throw new ApiException("Invalid response from server: " + status);
        }

        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();
        int readBytes;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }
        return new String(content.toByteArray());
    } catch (IOException e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

值得學的幾個習慣

User-Agent 要設定。 有些伺服器會拒絕空 UA 的請求,prepareUserAgent() 把套件名與版本組成字串,既禮貌又便於對方除錯。

例外要分類。 把「連不上」與「解析失敗」拆成 ApiException 與 ParseException,呼叫端才能給出有針對性的處理與訊息。

JSON 取不到就退回錯誤畫面。 matcher.find() 失敗時顯示 widget_message 版面,而不是讓 Widget 一片空白——使用者至少知道發生了什麼。

記得補上網路權限。 AndroidManifest.xml 需要 android.permission.INTERNET,這個範例若忘了就會在執行期拿到 SecurityException。

整體來說,這個範例的價值在於示範一條完整的資料流:抓字串 → 解析 JSON → 正則抽欄位 → 更新 RemoteViews → 綁定點擊行為。理解了這條鏈,換成任何 REST API 都是同樣的套路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved