編輯:Android 開發實例
從網路下載圖片顯示在畫面上,是專案裡很常遇到的需求。這裡整理兩個版本:先是最基本的寫法,再補上進度條以改善等待時的使用者體驗。
兩個版本都需要在 AndroidManifest.xml 加上網路權限:<uses-permission android:name="android.permission.INTERNET" />。
版面很簡單,一個置中的 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">
<ImageView
android:id="@+id/imgPic"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center|center_vertical"
android:src="@drawable/icon" />
</LinearLayout>
public class DownloadImage extends Activity {
private ImageView imgPic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image);
imgPic = (ImageView) findViewById(R.id.imgPic);
String url = "https://example.com/pic.jpg";
loadRemoteImage(url);
}
/** 下載遠端圖片 */
private Bitmap loadRemoteImage(String imgUrl) throws IOException {
URL fileURL = new URL(imgUrl);
HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
int length = (int) conn.getContentLength();
if (length == -1) {
return null; // 拿不到長度就無法預先配置緩衝
}
byte[] imgData = new byte[length];
byte[] buffer = new byte[512];
int readLen, destPos = 0;
while ((readLen = is.read(buffer)) > 0) {
System.arraycopy(buffer, 0, imgData, destPos, readLen);
destPos += readLen;
}
return BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
}
}
這裡有個必須修正的問題:原範例直接在 onCreate 裡下載,而網路請求在 Android 3.0 之後被嚴格禁止在主執行緒執行,會直接拋出 NetworkOnMainThreadException。正確做法是把下載放到背景執行緒,完成後再切回主執行緒更新 UI——也就是下面第二個版本要做的事。
網路慢或圖片大時,畫面會空白一片,使用者往往以為程式當掉了。加一條進度條,就能明確告知「正在進行中」。
public class DownloadImageWithProgress extends Activity {
private ImageView imgPic;
private ProgressBar progressBar;
private Handler mHandler;
private Bitmap bitmap = null;
private int totalSize = 0;
private int size = 0;
private String url = "https://example.com/pic.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image);
imgPic = (ImageView) findViewById(R.id.imgPic);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
mHandler = new Handler() {
public void handleMessage(Message msg) {
progressBar.setProgress(getProgressInt(progressBar.getMax()));
if (bitmap != null) {
imgPic.setImageBitmap(bitmap);
}
}
};
new Thread() {
public void run() {
loadRemoteImage(url);
}
}.start();
}
private void loadRemoteImage(String imgUrl) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(imgUrl).openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
int length = (int) conn.getContentLength();
totalSize = length;
if (length != -1) {
byte[] imgData = new byte[length];
byte[] buffer = new byte[512];
int readLen, destPos = 0;
while ((readLen = is.read(buffer)) > 0) {
System.arraycopy(buffer, 0, imgData, destPos, readLen);
destPos += readLen;
size = destPos;
mHandler.sendEmptyMessage(1); // 通知 UI 更新進度
Thread.sleep(100);
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
mHandler.sendEmptyMessage(1);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private int getProgressInt(int max) {
return (totalSize > 0) ? (int) (size * max * 1.0 / totalSize) : 0;
}
}
[下載中效果圖]
[下載完成效果圖]
第一,Thread.sleep(100) 只是為了讓動畫看得清楚,正式環境請拿掉,改為降低發送訊息的頻率即可,否則會拖慢下載。
第二,圖片應該快取到本機,避免每次進入頁面都重新下載;同時要注意 ImageView 顯示大圖容易 OutOfMemoryError,實務上會先用 BitmapFactory.Options 的 inJustDecodeBounds 讀取尺寸,再按目標檢視大小做 inSampleSize 縮放。
第三,現行專案通常不會自己寫這一整套。成熟的做法是用 Glide、Picasso 或 Coil 這類圖片載入庫,下載、快取、解碼、縮放、生命週期管理與進度顯示都已處理好;上面這些程式碼的價值在於理解底層流程,以及在没有第三方套件可用時能自己動手。
Android 進階:用 BLE 開發搜索 iBeacon 基站
前文講述了 Android 手機與 BLE 終端之間的通信,而最常見的 BLE 終端,莫過於蘋果公司倡導的 iBeacon 基站。iBeacon 技術基於 BLE,其特點
Android 登入畫面設計:帳密輸入與嘗試次數限制
設計登入畫面時,除了視覺配置,也要考慮互動流程。使用者輸入帳密後,系統應立即給予明確回饋。 密碼輸入 密碼欄位需要遮蔽輸入內容,避免旁人窺見。Android 可透過輸入型
Android 接入新浪微博、騰訊微博與人人網的 OAuth 2.0 實作
許多 Android 應用會需要接入社交平台的分享、登入或發文能力。本文以新浪微博、騰訊微博與人人網為例,說明整合時最關鍵的授權流程,以及如何取得後續呼叫 API 所需的
Android Service 元件案例分析
Service 是在背景執行、不與使用者直接互動的元件。它適合播放音樂、下載檔案、同步資料等任務。 兩種啟動方式 startService 啟動的服務會獨立執行,直到 s