編輯:關於 Android 程式設計
Android 中實作異步機制主要有兩條路:Thread 搭配 Handler,以及 AsyncTask。本文記錄 AsyncTask 的學習過程,以備日後查閱。
AsyncTask<Params, Progress, Result> 是一個抽象類別,通常作為父類被繼承。繼承時必須指定三個泛型參數:
一個異步任務的生命週期通常由這四個方法串起來:
publishProgress(Progress...) 回報進度。關鍵設計在於:只有 doInBackground 跑在背景執行緒,其餘三個都在 UI 執行緒。這正是 AsyncTask 的價值——它把執行緒切換的細節封裝起來,開發者只需覆寫方法即可。
官方文件列出幾條硬性約束:
Threading rules There are a few threading rules that must be followed for this class to work properly: 1. The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN. 2. The task instance must be created on the UI thread. 3. execute(Params...) must be invoked on the UI thread. 4. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. 5. The task can be executed only once (an exception will be thrown if a second execution is attempted).
翻譯成實務語言就是:
execute() 必須在 UI 執行緒中呼叫先來看成果。這個 demo 的重點是點擊後異步下載一張網路圖片,並在過程中顯示進度百分比,涵蓋了 I/O 操作與網路請求等知識點。

圖一:首頁,點擊按鈕進入載入頁面
圖二:載入過程中顯示的進度百分比
圖三:進度達 100% 後顯示完整圖片
主介面就是一個按鈕加上頁面跳轉。載入頁的布局用 RelativeLayout 疊放三個元件:ImageView 顯示圖片、ProgressBar 顯示進度、TextView 顯示百分比。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<TextView
android:id="@+id/mTextprogress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="15%"
android:textSize="13sp" />
</RelativeLayout>
package com.example.asynctaskdemo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
/**
* 異步載入並顯示一張網路圖片
*/
public class ImageTest extends Activity {
private String TAG = ImageTest.class.getSimpleName();
private ImageView mImageView;
private ProgressBar mProgressBar;
private TextView mTextProgress;
private MyAsyncTaskShowImg mTask;
private static String mImgUrl = "https://h.hiphotos.baidu.com/image/pic/item/"
+ "9922720e0cf3d7ca14dcc750f71fbe096b63a9ea.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
initView();
mTask = new MyAsyncTaskShowImg();
mTask.execute(mImgUrl);
}
private void initView() {
mTextProgress = (TextView) findViewById(R.id.mTextprogress);
mImageView = (ImageView) findViewById(R.id.imageView1);
mProgressBar = (ProgressBar) findViewById(R.id.progress);
}
class MyAsyncTaskShowImg extends AsyncTask<String, Integer, Bitmap> {
/** 初始化 UI 元件 */
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
mTextProgress.setText("0%");
}
/** 執行耗時的背景作業 */
@Override
protected Bitmap doInBackground(String... params) {
String mImgUrl = params[0];
String mFileName = "temp_pic";
Log.d(TAG, "mImgUrl is " + mImgUrl);
Bitmap mBitmap = null;
InputStream is = null;
OutputStream out = null;
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(mImgUrl).openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setConnectTimeout(10 * 1000);
is = connection.getInputStream();
out = openFileOutput(mFileName, MODE_PRIVATE);
byte[] data = new byte[1024];
int seg = 0;
long totalSize = connection.getContentLength();
Log.d(TAG, "total size is " + totalSize);
long current = 0;
while (!isCancelled() && (seg = is.read(data)) != -1) {
current += seg;
Log.d(TAG, "current size is " + current);
int progress = (int) ((float) current / totalSize * 100);
Log.d(TAG, "progress size is " + progress);
// 回報進度,會觸發 onProgressUpdate
publishProgress(progress);
out.write(data, 0, seg);
}
mBitmap = BitmapFactory.decodeFile(
getFileStreamPath(mFileName).getAbsolutePath());
Log.d(TAG, "file is " + getFileStreamPath(mFileName).getAbsolutePath());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 收尾工作放在 finally 中,確保連線與串流一定被關閉
if (out != null) {
try { out.close(); } catch (IOException e) { }
}
if (is != null) {
try { is.close(); } catch (IOException e) { }
}
if (connection != null) {
connection.disconnect();
}
}
return mBitmap;
}
/** 更新載入進度 */
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mTextProgress.setText(values[0] + "%");
}
/** 把 doInBackground 的結果回傳到 UI 執行緒 */
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
mProgressBar.setVisibility(View.GONE);
mTextProgress.setVisibility(View.GONE);
mImageView.setImageBitmap(result);
Toast.makeText(ImageTest.this, "圖片加載完成。", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPause() {
super.onPause();
if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
// cancel() 只是把狀態標記為 cancelled,並不會真的中止背景執行緒
mTask.cancel(true);
}
}
}
先存檔再解碼。這裡沒有直接把串流轉成 Bitmap,而是先寫入內部檔案,再用 BitmapFactory.decodeFile() 讀回。這樣做的好處是記憶體峰值較低,也讓圖片有了本地快取,第二次進入頁面不必重新下載。
進度計算要防溢位與除零。(int) ((float) current / totalSize * 100) 先轉 float 再運算,避免大數相乘溢位;若伺服器未回傳 Content-Length,totalSize 會是 -1,此時除法結果沒有意義,應另外處理這種情況。
cancel() 不是真的中止。呼叫 cancel(true) 只是把任務狀態改為 cancelled,正在進行的 I/O 不會立刻停下。因此迴圈中要主動檢查 isCancelled() 才有意義,範例已加上這個判斷。
資源釋放要放 finally。原始範例把 close 寫在 try 區塊末尾,一旦中途拋出例外就會跳過,造成串流洩漏。上面已改寫為 finally 區塊。
AsyncTask 已被標記為 deprecated。從 API 30 起 AsyncTask 不再建議使用。新專案若要處理網路請求,建議改用 Kotlin 協程、Retrofit、OkHttp 搭配 LiveData/Flow,或 WorkManager(適合需要保證完成或由系統代管的背景工作)。若只是單純載入圖片,直接使用 Glide、Picasso、Coil 這類成熟框架會省下大量功夫。
Android Studio 中的 UnsatisfiedLinkError:兩個真正容易忽略的原因
最近在處理一個需要解析影片位址的專案,其中一段解密邏輯是以 JNI 實作、透過对应的 key 才能還原資料。以前用 Eclipse 時,把 .so 放進 libs/arm
Android 調試技巧:手動配置 adb 的 USB 連接
問題背景 換了一台測試機,Android Studio 死活認不出設備,adb devices 列表空空如也。這類問題大多不是驅動壞了,而是 adb 並不知道該用哪個廠商
把 Android 開源專案發佈到 JCenter 的完整流程與踩坑筆記
我們每天都在 build.gradle 裡寫 compile com.android.support:design:23.4.0,一行字就把別人的成果拉進自己的專案。那反
小米推送接入實記:從後台建項到代碼落地的完整流程
公司項目需要接入推送,技術選型後我們用了小米推送。從註冊帳號到消息真正落到通知欄,中間踩了不少流程上的坑,這裡把完整步驟記錄下來。 一、後台配置 1、註冊並登入小米開放