編輯:關於 Android 程式設計
本篇教學帶大家如何在 MyEclipse 中搭建一個簡單的服務端,並透過手機端與其通信、異步加載資料。
筆者使用的是 MyEclipse,各位也可以直接用 Eclipse 建立 Java Web 專案。Google 提供的 ADT Bundle 無法建立 Web 專案,讀者可下載 Eclipse For JavaEE Developer 這個 IDE。以下介紹如何在 MyEclipse 建立 Web 專案並部署到 Tomcat(Tomcat 的設定這裡不多說明)。
建立一個名為 Test 的 Web 專案,專案結構如下:

我建立了一個 images 資料夾和 list.xml 檔,images 存放一些圖片(也就是稍後要取得的),list.xml 內容如下:
青蛙1 /images/frog1.gif ... 青蛙2 /images/frog2.gif
最外層是 contacts 標籤,裡面有多個子 contact 標籤,每個子標籤包含 id、name 和 image 內容,對應稍後要解析的 Contact 物件。
這裡要提醒:image 標籤的 src 是圖片網址,這個位址是 PC 的 IP,讀者測試時需將它改為自己電腦的 IP。取得方式:執行 → cmd → ipconfig /all,查看 IPv4 位址就是你的電腦 IP。

建立好 Web 專案後,在瀏覽器輸入位址 https://你的IP:8080/Test/list.xml 測試:

能看到上述內容,代表已能訪問到服務端,接下來即可開發客戶端。這裡建立名為 07_DataAsyncLoad 的專案。
由於需要聯網,在 AndroidManifest.xml 設定權限:
根據服務端 list.xml,我們定義一個實體類 Contact:
package com.wwj.domain; /** * 聯系人實體類 */ public class Contact { public int id; public String name; public String image; public Contact(int id, String name, String image) { this.id = id; this.name = name; this.image = image; } public Contact() { } }
由於需要訪問服務端並解析 xml,我們定義一個服務類 ContactService:
package com.wwj.service; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import com.wwj.domain.Contact; import com.wwj.utils.MD5; import android.net.Uri; import android.util.Xml; public class ContactService { /** * 獲取聯系人 */ public static List getContacts() throws Exception{ String path = "https://你的IP:8080/Test/list.xml"; HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){ return parseXML(conn.getInputStream()); } return null; } /** * 利用pull解析器對xml文件進行解析 */ private static List parseXML(InputStream xml) throws Exception{ List contacts = new ArrayList(); Contact contact = null; XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(xml, "UTF-8"); int event = pullParser.getEventType(); while(event != XmlPullParser.END_DOCUMENT){ switch (event) { case XmlPullParser.START_TAG: if("contact".equals(pullParser.getName())){ contact = new Contact(); contact.id = new Integer(pullParser.getAttributeValue(0)); }else if("name".equals(pullParser.getName())){ contact.name = pullParser.nextText(); }else if("image".equals(pullParser.getName())){ contact.image = pullParser.getAttributeValue(0); } break; case XmlPullParser.END_TAG: if("contact".equals(pullParser.getName())){ contacts.add(contact); contact = null; } break; } event = pullParser.next(); } return contacts; } /** * 獲取網絡圖片,如果圖片存在於緩存中就返回,否則從網絡加載並緩存 */ public static Uri getImage(String path, File cacheDir) throws Exception{ File localFile = new File(cacheDir, MD5.getMD5(path)+ path.substring(path.lastIndexOf("."))); if(localFile.exists()){ return Uri.fromFile(localFile); }else{ HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){ FileOutputStream outStream = new FileOutputStream(localFile); InputStream inputStream = conn.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inputStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); } inputStream.close(); outStream.close(); return Uri.fromFile(localFile); } } return null; } }
上述程式碼大致流程是:傳入一個網路路徑,透過 URL 開啟連接、以 HttpURLConnection 連接服務端取得輸入流,再用 XmlPullParser 解析 xml 取得資料。
取得網路圖片時需進行 MD5 加密計算,如下:
package com.wwj.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { public static String getMD5(String content) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(content.getBytes()); return getHashString(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private static String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } }
服務類寫完後,在 MainActivity 進行異步加載資料:
package com.wwj.asyntask; import java.io.File; import java.util.List; import com.wwj.adapter.ContactAdapter; import com.wwj.domain.Contact; import com.wwj.service.ContactService; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.widget.ListView; public class MainActivity extends Activity { ListView listView; File cache; Handler handler = new Handler() { public void handleMessage(Message msg) { listView.setAdapter(new ContactAdapter(MainActivity.this, (List) msg.obj, R.layout.listview_item, cache)); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) this.findViewById(R.id.listView); cache = new File(Environment.getExternalStorageDirectory(), "cache"); if (!cache.exists()) cache.mkdirs(); // 開一個線程來加載數據 new Thread(new Runnable() { public void run() { try { List data = ContactService.getContacts(); handler.sendMessage(handler.obtainMessage(22, data)); } catch (Exception e) { e.printStackTrace(); } } }).start(); } @Override protected void onDestroy() { for (File file : cache.listFiles()) { file.delete(); } cache.delete(); super.onDestroy(); } }
這裡開了一個線程來加載資料,是因為網路操作不能在 UI 執行緒中進行;加載完畢後透過 Handler 發送訊息,顯示列表。
圖片加載通常需另外處理,最常用的是 Handler+Thread 和 AsyncTask 兩種。以下在自訂的 ContactAdapter 中用 AsyncTask 實現圖片異步加載:
package com.wwj.adapter; import java.io.File; import java.util.List; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.wwj.domain.Contact; import com.wwj.service.ContactService; public class ContactAdapter extends BaseAdapter { private List data; private int listviewItem; private File cache; LayoutInflater layoutInflater; public ContactAdapter(Context context, List data, int listviewItem, File cache) { this.data = data; this.listviewItem = listviewItem; this.cache = cache; layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return data.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = null; TextView textView = null; if (convertView == null) { convertView = layoutInflater.inflate(listviewItem, null); imageView = (ImageView) convertView.findViewById(R.id.imageView); textView = (TextView) convertView.findViewById(R.id.textView); convertView.setTag(new DataWrapper(imageView, textView)); } else { DataWrapper dataWrapper = (DataWrapper) convertView.getTag(); imageView = dataWrapper.imageView; textView = dataWrapper.textView; } Contact contact = data.get(position); textView.setText(contact.name); asyncImageLoad(imageView, contact.image); return convertView; } private void asyncImageLoad(ImageView imageView, String path) { AsyncImageTask asyncImageTask = new AsyncImageTask(imageView); asyncImageTask.execute(path); } /** * 使用AsyncTask異步加載圖片 */ private final class AsyncImageTask extends AsyncTask { private ImageView imageView; public AsyncImageTask(ImageView imageView) { this.imageView = imageView; } protected Uri doInBackground(String... params) { try { return ContactService.getImage(params[0], cache); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(Uri result) { if (result != null && imageView != null) imageView.setImageURI(result); } } private final class DataWrapper { public ImageView imageView; public TextView textView; public DataWrapper(ImageView imageView, TextView textView) { this.imageView = imageView; this.textView = textView; } } }
以上就是本專案所有程式碼,執行專案效果如下:

Android 仿支付寶手勢密碼解鎖功能實作
起步(Starting)建立手勢密碼可參考 CreateGestureActivity.java 檔案;登入時驗證手勢密碼則可參考 GestureLoginActivit
Android 自定義 View:手寫簽名板實作
概述 本文透過自定義 View 實現一個 Android 手寫簽名板,支持透明背景、貝塞爾平滑曲線,並能對最終結果進行邊緣空白裁剪。 自定義 LinePathView 核
Android 數據存儲之 SQLite 數據庫詳解
前言 Android 提供了多種數據存儲方式。少量數據用 SharedPreferences 或文件存儲即可;但當需要讀寫大量數據時,就得用上數據庫了。Android 內
Android 自定義 View:繪製選手實力雷達圖
導語 繪製雷達圖是自定義 View 的經典練習題,網上也有不少相關案例。掌握思路後,你可以按需修改代碼並集成到自己的項目中。 效果預覽: 核心代碼 自定義 View 的