Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎筆記:網絡訪問與異步消息處理入門

編輯:關於 Android 程式設計

這份筆記把網絡訪問、異步消息處理以及一個模仿新聞客戶端的小案例串了起來,涵蓋 GET/POST 提交數據等常見場景,適合入門鞏固。

訪問網絡資源的基本步驟

Android 中獲取網絡資源最基礎的方式,可以拆成四步:

① 通過 URL.openConnection() 拿到一個 HttpURLConnection 連接對象;
② 配置連接參數,例如超時時間、請求方式(HttpURLConnection 默認是 GET);
③ 獲取服務器響應碼,並據此判斷後續操作;
④ 響應成功後,從 conn.getInputStream() 取得響應流並進行處理。

 try { URL url = new URL(path); // 1. 獲取一個HttpURLConnection鏈接對象,通過調用URL.openConnection() HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 2. 設置網絡鏈接對象的一些參數 conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); // 3. 獲取服務器的響應碼 int responseCode = conn.getResponseCode(); if (200 == responseCode) { // 響應成功 // 4. 解析相應結果 InputStream is = conn.getInputStream(); } } catch (Exception e) { e.printStackTrace(); }

兩個必須牢記的坑

★ 在主線程裡直接寫網絡訪問,會拋出 android.os.NetworkOnMainThreadException。解決辦法很直接:把網絡請求放到子線程執行。

★ 試圖在子線程裡更新 UI,會拋出 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.。異常信息說得很明白——視圖層級只能由創建它的主線程(UI 線程)來操作。

這兩個限制加在一起,就催生了 Android 的異步消息處理機制,核心就是 Handler 與 Message。

異步消息處理的幾種用法

典型場景是:在子線程裡請求網絡、拿到數據,再切回主線程更新界面。實現方式有好幾種。

方式一:Handler + Message

① 實例化 Handler 並重寫 handleMessage():

 private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { // 處理消息 }; };

② 在子線程中創建並發送消息:

 // 獲取消息的方式有多種 // Message msg = new Message(); // Handler.obtainMessage() // 但是谷歌的建議是:While the constructor of Message is public, the best way to get one of these is to call Message.obtain() or one of the Handler.obtainMessage() methods, Message msg = Message.obtain(); msg.obj = result; handler.sendMessage(msg);

方式二:調用 Activity.runOnUiThread()

 runOnUiThread(new Runnable() { @Override public void run() { // 更新UI } });

方式三:調用 View 的 post() 方法

 tv_content.post(new Runnable() { @Override public void run() { // 更新UI tv_content.setText(result); } });

方式四:Handler 的 post() 方法

 private Handler handler = new Handler();
 handler.post(new Runnable() { @Override public void run() { // 更新UI tv_content.setText(result); } });

方式雖多,但背後原理是相通的,最終都離不開異步消息機制。對比一下源碼就更清楚了。

Handler 的 post:

  public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }

View 的 post:

 public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; }

Activity 的 runOnUiThread:

 public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }

是不是驚人地相似?歸根結底,它們都在往同一個 Handler 裡投遞任務。

為什麼這樣就能操作 UI?

關鍵在於 Handler 總是依附於創建時所處的線程。我們的 Handler 在主線程中創建,子線程雖然不能直接碰 UI,但可以通過發送消息、入隊、出隊等一系列環節,最終在 Handler 的 handleMessage() 裡被調度執行——而這個方法此時已經跑在主線程上了,自然就能安全地更新界面。

模仿新聞客戶端小案例

為了把前面的知識串聯起來,可以動手做一個模仿網易新聞的簡易客戶端。

涉及的知識點包括:RelativeLayout 相對布局、HttpUrlConnection 請求網絡、XmlPullParser 解析 XML、ListView 展示數據、BaseAdapter 適配器,以及 Handler/Message 異步消息處理。

開發步驟大致如下:① 約定客戶端與服務端的數據格式為 XML;② 確認服務端資源可訪問;③ 畫主界面 UI;④ 畫列表項 UI;⑤ 請求網絡拿到結果流;⑥ 解析 XML 得到數據集合;⑦ 編寫 ListView 適配器。

先確定服務端返回的 XML 結構:

   國家發改委副主任朱之鑫【關鍵詞:霧霾天】歐V推行辦法正在研究中朱之鑫說,霧霾天氣有三方面成因:一是中國高耗能產業和高污染產業較多,如水泥、制造業、鋼鐵等行業,在華北地區分布較多;二是和大規模建設有關,工地上未覆蓋苫布造成揚塵;三是汽車尾氣增加了細微顆粒物排放。民盟中央提交的一份關於大氣污染治理的提案  https://192.168.1.100:8080/img/a.jpg 1 163   

② 確認服務端資源可訪問


③ 主界面 UI,裡面只放一個 ListView:

    

④ 列表項 UI:

       

⑤ 請求網絡、拿到結果流:

 /** * 請求數據 */ private void initData() { // 子線程 new Thread(new Runnable() { @Override public void run() { // 訪問網絡 try { // 獲取鏈接對象 URL url = new URL(dataPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 配置鏈接對象 conn.setReadTimeout(5 * 1000); conn.setRequestMethod("GET"); // 獲取響應碼 int responseCode = conn.getResponseCode(); if (responseCode == 200) { // 獲取結果流 InputStream is = conn.getInputStream(); // 獲取到集合 newsBeanList = parserXML(is); // 發送消息表明數據獲取成功 handler.sendEmptyMessage(SUCCESS); } } catch (Exception e) { e.printStackTrace(); } } }).start(); }

⑥ 解析 XML,封裝成數據集合:

 /** * 解析XML數據,並將數據封裝到實體bean中 * * @param is * @return * @throws Exception */ private List parserXML(InputStream is) throws Exception { // 獲取到解析器 XmlPullParser parser = Xml.newPullParser(); // 設置解析器的參數 parser.setInput(is, "UTF-8"); // 獲取到事件 int eventType = parser.getEventType(); // 定義 List newsBeanList = null; NewsBean newsBean = null; // 循環處理事件,並封裝成為實體bean while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: if ("channel".equals(parser.getName())) { // 初始化集合 newsBeanList = new ArrayList(); } else if ("item".equals(parser.getName())) { // 初始化bean newsBean = new NewsBean(); } else if ("title".equals(parser.getName())) { newsBean.setTitle(parser.nextText()); } else if ("description".equals(parser.getName())) { newsBean.setDescription(parser.nextText()); } else if ("image".equals(parser.getName())) { newsBean.setImage(parser.nextText()); } else if ("type".equals(parser.getName())) { newsBean.setType(parser.nextText()); } else if ("comment".equals(parser.getName())) { newsBean.setComment(parser.nextText()); } break; case XmlPullParser.END_TAG: if ("item".equals(parser.getName())) { // 將bean添加到集合中 newsBeanList.add(newsBean); } else if ("channel".equals(parser.getName())) { // 返回集合 return newsBeanList; } break; default: break; } // 循環事件 eventType = parser.next(); } return null; }

⑦ 編寫 ListView 適配器,圖片加載處使用了 SmartImageView 開源庫:

 class MyAdapter extends BaseAdapter { @Override public int getCount() { return newsBeanList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (convertView == null) { view = View.inflate(getApplicationContext(), R.layout.item, null); } else { view = convertView; } SmartImageView iv_icon = (SmartImageView) view.findViewById(R.id.iv_icon); TextView tv_title = (TextView) view.findViewById(R.id.tv_title); TextView tv_content = (TextView) view.findViewById(R.id.tv_content); TextView tv_type = (TextView) view.findViewById(R.id.tv_type); // 獲取集合中的數據,顯示到控件上 NewsBean bean = newsBeanList.get(position); tv_title.setText(bean.getTitle()); tv_content.setText(bean.getDescription()); tv_type.setText(bean.getType()); iv_icon.setImageUrl(bean.getImage().replace("192.168.1.100", localhost)); return view; } }

⑧ 通過異步消息處理為 ListView 設置適配器:

 private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == SUCCESS) { // 為ListView設置適配器 lv.setAdapter(new MyAdapter()); } }; };

GET 方式提交數據

把參數拼接到 URL 上,是最直觀的 GET 請求:

 String username = et_username.getText().toString().trim(); String password = et_password.getText().toString().trim(); final String path = "https://192.168.1.101:8080/web/LoginServlet?username=" + username + "&password=" + password; // 子線程 new Thread(new Runnable() { @Override public void run() { // 訪問網絡 try { // 獲取鏈接對象 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 配置鏈接對象 conn.setReadTimeout(5 * 1000); conn.setRequestMethod("GET"); // 獲取響應碼 int responseCode = conn.getResponseCode(); if (responseCode == 200) { // 獲取結果流 InputStream is = conn.getInputStream(); String result = streamToString(is); showToast(result); } } catch (Exception e) { e.printStackTrace(); } } }).start();

POST 方式提交數據

POST 與 GET 相比只多了一小段差異:需要設置請求頭並把數據寫入輸出流。

 final String username = et_username.getText().toString().trim(); final String password = et_password.getText().toString().trim(); final String path = "https://192.168.1.101:8080/web/LoginServlet"; // 子線程 new Thread(new Runnable() { @Override public void run() { // 訪問網絡 try { // 獲取鏈接對象 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 配置鏈接對象 conn.setReadTimeout(5 * 1000); conn.setRequestMethod("POST"); // ☆ 不同之處:設置POST請求的頭信息 String data = "username=" + username + "&password=" + password; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length() + ""); // ☆ 不同之處:發送數據 conn.setDoOutput(true); conn.getOutputStream().write(data.getBytes()); // 獲取響應碼 int responseCode = conn.getResponseCode(); if (responseCode == 200) { // 獲取結果流 InputStream is = conn.getInputStream(); String result = streamToString(is); showToast(result); } } catch (Exception e) { e.printStackTrace(); } } }).start();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved