編輯:關於 Android 程式設計
Android 非同步任務的本質,是在背景開啟一個執行緒完成耗時操作,而 onPreExecute 與 onPostExecute 等方法則運行於 UI 主執行緒,用來更新介面。為了提升使用者體驗,常見的非同步載入方式有以下兩種,以下分別說明。
效果如下:

關鍵程式碼:
/** 非同步任務為列表載入資料 */
private void fillData() {
new AsyncTask<Void, Void, Void>() {
@Override protected void onPreExecute() {
loading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override protected void onPostExecute(Void result) {
loading.setVisibility(View.INVISIBLE);
// 刷新列表資料
if (mAdapter == null) {
mAdapter = new RubishSmsInfosAdapter();
mRubishSms.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
super.onPostExecute(result);
}
@Override protected Void doInBackground(Void... params) {
if (mInfos == null) {
mInfos = mRubishSmsInfoDao.findInfosbyPage(maxNum, offset);
} else {
mInfos.addAll(mRubishSmsInfoDao.findInfosbyPage(maxNum, offset));
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
其中 loading = findViewById(R.id.ll_rubish_sms_info_loading);,版面檔如下:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="100" >
<LinearLayout android:layout_gravity="center" android:id="@+id/ll_rublish_sms_info_loading"
android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:visibility="invisible" >
<ProgressBar android:layout_width="match_parent" android:layout_height="wrap_content" />
<TextView android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="數據加載中,請稍後..." android:textSize="13sp" />
</LinearLayout>
</FrameLayout>
<ListView android:id="@+id/lv_rubish_sms_content" android:layout_width="match_parent" android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
透過上述程式碼即可實現載入中提示的效果。
效果圖:

以下以「手機病毒查殺」為例,展示非同步掃描並動態載入資料的邏輯:
/** 掃描病毒並動態顯示在介面 */
private void scanVirus() {
new AsyncTask<Void, Object, Void>() {
List<VirusApp> apps = new ArrayList<VirusApp>();
String desc = null;
Dialog dialog = new Dialog(KillVirusActivity.this);
View viewKilling = View.inflate(KillVirusActivity.this, R.layout.killing_dialog, null);
@Override protected void onPreExecute() {
mKillVirusResult.setText("正在掃描中,請稍等...");
dialog.setCancelable(false);
dialog.setContentView(viewKilling);
dialog.show();
pm = getPackageManager();
packageInfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_SIGNATURES);
super.onPreExecute();
}
@Override protected void onPostExecute(Void result) {
dialog.dismiss();
if (apps.size() > 0) {
mKillVirusResult.setTextColor(Color.RED);
mKillVirusResult.setText("掃描完成!發現病毒" + apps.size() + "個,請及時清理");
for (final VirusApp app : apps) {
View view = View.inflate(KillVirusActivity.this, R.layout.app_virus_info_item, null);
view.setClickable(true);
view.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("android.intent.action.DELETE");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + app.getmAppVirusName()));
startActivity(intent);
}
});
// 設定圖示、名稱、描述,此處省略
mContainer.addView(view);
}
} else {
mKillVirusResult.setText("掃描完成!恭喜沒有發現病毒!");
}
super.onPostExecute(result);
}
@Override protected Void doInBackground(Void... params) {
VirusDao virusDao = new VirusDao();
for (PackageInfo info : packageInfos) {
Signature[] signature = info.signatures;
try {
String md5 = Md5Util.encode(signature[0].toString());
desc = virusDao.findVirus(md5);
} catch (Exception e) { }
if (desc != null) {
VirusApp app = new VirusApp();
app.setmAppVirusIcon(pm.getApplicationIcon(info.applicationInfo));
app.setmAppVirusName((String) pm.getApplicationLabel(info.applicationInfo));
app.setmAPPVirusDesc(desc);
apps.add(app);
}
}
return null;
}
}.execute();
}
對應的 Activity 版面有一個 LinearLayout 容器,可實現動態載入資料的效果:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
<TextView android:layout_width="match_parent" android:layout_height="35dp" android:background="@drawable/ll_title_bg"
android:gravity="center" android:text="手機病毒查殺" />
<TextView android:id="@+id/tv_kill_virus_result" android:layout_width="match_parent" android:layout_height="125dp"
android:gravity="center" android:background="@drawable/ll_title_bg" />
<ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" >
<LinearLayout android:id="@+id/ll_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
自訂對話框版面則很單純,只有一個 ProgressBar 與提示文字:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
<ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"
android:text="病毒掃描中..." android:textSize="15sp" />
</LinearLayout>
整體邏輯在 onCreate 中先呼叫 copyVirusDB() 把本地病毒簽名庫複製到 app 目錄,再呼叫 scanVirus() 啟動非同步掃描。doInBackground 會遍歷裝置上所有應用的簽名,以 MD5 比對本地病毒庫,命中者收集成清單,最後在 onPostExecute 中動態加入容器並顯示結果。透過這種「背景運算 + 主執行緒刷新」的模式,就能在漫長的掃描過程中保持介面流暢並給予即時回饋。
Android App 整合 Mob 簡訊驗證碼:從申請到無 GUI 接入
為什麼選擇 Mob 簡訊驗證碼許多 App 在註冊、登入或通知時都需要簡訊能力。對個人開發者或小團隊而言,自行接電信服務成本較高,Mob 提供的簡訊驗證碼 SDK 是一個
Android 照片牆實作:用 LruCache 避免圖片太多導致崩潰
照片牆的常見問題照片牆是許多應用常見的展示形式,通常用 GridView 或其他可捲動容器呈現大量圖片。問題在於,當使用者不斷捲動時,若沒有適當的記憶體管理機制,圖片會持
vivo X7怎麼換字型?替換系統字型檔案的步驟與風險
有些使用者對 vivo X7 的系統預設字型不太滿意,想換成自己喜歡的樣式。這件事在 Android 上做得到,但需要解鎖系統權限並替換字型檔案,屬於高風險操作,請先讀完
在 Android 應用內瀏覽網頁:WebView 實作教學
有時候我們會希望在應用程式內部直接瀏覽網頁。雖然可以呼叫系統瀏覽器來開啟,但這種方式在許多情境下並不適用——例如想保留自訂的介面風格、需要攔截頁面載入事件,或單純不想跳出