編輯:Android 開發實例
本節動手做一個小程式:從伺服器抓一張圖片下載到本機,過程中彈出讀取進度提示,下載完成後再把圖片顯示在畫面上。整個流程使用多執行緒處理網路 IO,並內建「本地快取優先」的判斷邏輯,第二次開啟同一張圖時不必再走網路。
HttpURLConnection 連線並讀取圖片位元資料。Handler 把 UI 更新送回主執行緒。ProgressDialog 呈現讀取中的等待狀態。If-Modified-Since 做 304 判定。點擊按鈕後另開一條執行緒抓取圖片,抓之前先跳進度框,抓完再關掉並設定 ImageView。所有涉及介面的操作都包在 handler.post() 裡,因為子執行緒不能直接改 UI。
package cn.itcast.pic;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class mainActivity extends Activity {
private TextView addressET;
private ImageView imageIV;
private Handler handler = new Handler(); // 在主執行緒建立 Handler
private ProgressDialog dialog;
private ImageService service;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addressET = (TextView) this.findViewById(R.id.addressET);
imageIV = (ImageView) this.findViewById(R.id.imageIV);
service = new ImageService(this);
}
public void onClick(View v) {
// 網路下載放到新執行緒,避免阻塞主執行緒
new Thread() {
public void run() {
try {
String address = addressET.getText().toString();
// 透過匿名 Runnable 把「顯示進度框」丟回主執行緒執行
handler.post(new Runnable() {
public void run() {
dialog = new ProgressDialog(mainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("請稍候...");
dialog.setCancelable(false); // 不允許使用者取消
dialog.show();
}
});
// 耗時的網路讀取在新執行緒中進行
final Bitmap image = service.getImage(address);
handler.post(new Runnable() {
public void run() {
dialog.dismiss();
imageIV.setImageBitmap(image); // 更新 UI 必須回到主執行緒
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "服務器忙,請稍後再試!", 0).show();
}
}
}.start();
}
}
這支類別負責真正的網路溝通與快取策略:
package cn.itcast.pic;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
public class ImageService {
private Context context;
public ImageService(Context context) {
super();
this.context = context;
}
public Bitmap getImage(String address) throws Exception {
// 1. 以 URL 物件封裝位址並建立連線
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
// 2. 判斷是否已有快取檔
File cacheFile = new File(context.getCacheDir(),
URLEncoder.encode(address));
if (cacheFile.exists()) {
// 帶入快取檔最後修改時間,讓伺服器決定是否回 304
conn.setIfModifiedSince(cacheFile.lastModified());
}
// 3. 依狀態碼決定後續動作
int code = conn.getResponseCode();
if (code == 200) {
byte[] data = Util.read(conn.getInputStream());
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
weiteCache(cacheFile, bm);
return bm;
} else if (code == 304) {
// 圖片沒有變動,直接讀本地快取
return BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
}
// 其他狀態碼一律視為錯誤
throw new NetworkErrorException("訪問服務器出錯:" + code);
}
// 4. 另開執行緒寫入快取,避免拖累畫面顯示
private void weiteCache(final File cacheFile, final Bitmap bm) {
new Thread() {
public void run() {
try {
FileOutputStream fos = new FileOutputStream(cacheFile);
bm.compress(CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
}
}
把 InputStream 逐段讀進 ByteArrayOutputStream,最後一次轉成位元組陣列,交給 BitmapFactory 解碼。
package cn.itcast.pic;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Util {
public static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
return baos.toByteArray();
}
}
上方一列是輸入位址的 EditText 與觸發下載的按鈕,下方 ImageView 用來呈現結果。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/addressET"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textEmailAddress" >
<requestFocus />
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text=" GO " />
</LinearLayout>
<ImageView
android:id="@+id/imageIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
一是要在 AndroidManifest.xml 加上 android.permission.INTERNET 權限,否則連線會直接失敗;二是快取檔案建議後續加上大小上限與過期清理,避免長期使用佔滿應用程式可用的儲存空間。
Android 本地化指南:讓應用適應不同語言環境
Android 應用可能在不同語言環境的裝置上執行。若要讓應用更貼近使用者,應將文字、數字與其他資源本地化。最常見的做法是把字串放入不同 values 資料夾。 建立本地
Android 多語言本地化完整指南
一款 Android 應用往往會在不同國家、各種裝置上運行,使用者來自各地。要讓應用更具親和力,就必須針對當前語言環境妥善處理文字、數字、檔案等內容,這正是本地化的核心目
第三方應用接入微信平台研究分享(一):SDK 結構與通信流程
微信平台開放之後,不少第三方應用都想接進來——畢竟能借用微信建立起來的人際鏈來擴展自己的應用,確實比自己從零經營社交省下可觀的成本。由於實習需要,我最近也在研究這塊,不過
Android 剪貼板(Clipboard)實作教學:複製與貼上各種資料型別
Android 內建的剪貼板框架(Clipboard Framework)提供了一套通用的複製/貼上機制,不只純文字,也能處理圖片、二進位資料流,甚至 URI 與 Int