編輯:關於 Android 程式設計
AsyncTask 是 Android 提供的輕量級異步工具類。繼承它之後,把耗時操作放進指定方法,就能透過內建的回調把執行進度與最終結果回報給 UI 主執行緒,不必自己管理執行緒與 Handler。
doInBackground(Params...)——在背景執行緒跑,所有耗時工作都放在這裡。注意:這個方法不能直接操作 UI。若中途想更新進度,可以呼叫 publishProgress(Progress...)。
onPostExecute(Result)——在主執行緒執行,參數就是 doInBackground() 的回傳值,用來把結果呈現到畫面上。
AsyncTask<Params, Progress, Result>
・Params:啟動任務時傳入的輸入參數類型。
・Progress:背景任務的進度類型。
・Result:背景計算結果的類型。
package com.example.asynctasktest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button satrtButton;
private Button cancelButton;
private ProgressBar progressBar;
private TextView textView;
private DownLoaderAsyncTask downLoaderAsyncTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
public void initView() {
satrtButton = (Button) findViewById(R.id.startButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
satrtButton.setOnClickListener(new ButtonOnClickListener());
cancelButton.setOnClickListener(new ButtonOnClickListener());
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
}
private class ButtonOnClickListener implements OnClickListener {
public void onClick(View v) {
switch (v.getId()) {
case R.id.startButton:
// 注意三件事:
// 1. 每次都要 new 一個實例,同一個任務只能執行一次
// 2. 異步任務的實例必須在 UI 執行緒中建立
// 3. execute() 必須在 UI 執行緒中呼叫
downLoaderAsyncTask = new DownLoaderAsyncTask();
downLoaderAsyncTask.execute("https://www.baidu.com");
break;
case R.id.cancelButton:
// 取消正在執行的任務,onCancelled() 會被回調
downLoaderAsyncTask.cancel(true);
break;
default:
break;
}
}
}
private class DownLoaderAsyncTask extends AsyncTask<String, Integer, String> {
// 執行異步任務前,主線程的準備工作
@Override
protected void onPreExecute() {
super.onPreExecute();
textView.setText("調用onPreExecute()方法--->准備開始執行異步任務");
}
// 背景執行,不可在這裡更新 UI
@Override
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
long total = entity.getContentLength();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
int length = -1;
while ((length = is.read(buffer)) != -1) {
bos.write(buffer, 0, length);
count += length;
// 通知主線程目前的進度,會觸發 onProgressUpdate()
publishProgress((int) ((count / (float) total) * 100));
// 為了方便觀察進度,故意睡 1 秒
Thread.sleep(1000);
}
return new String(bos.toByteArray(), "UTF-8");
}
} catch (Exception e) {
return null;
}
return null;
}
// 任務完成後,在主線程處理結果
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
"調用onPostExecute()方法--->異步任務執行完畢", 0).show();
textView.setText(result);
}
// 更新進度,在主線程執行
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
textView.setText("已經加載" + values[0] + "%");
}
// 任務被取消時執行
@Override
protected void onCancelled() {
super.onCancelled();
progressBar.setProgress(0);
textView.setText("調用onCancelled()方法--->異步任務被取消");
}
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="開始異步任務" />
<Button
android:id="@+id/cancelButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="取消異步任務" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0" />
<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="test test" />
</ScrollView>
</LinearLayout>
整個生命週期依序是:onPreExecute() → doInBackground()(其間可多次呼叫 publishProgress() 觸發 onProgressUpdate())→ onPostExecute()。若中途呼叫 cancel(true),則會跳到 onCancelled() 而不再執行 onPostExecute()。
一個實例只能跑一次。同一個 AsyncTask 物件第二次呼叫 execute() 會拋出 IllegalStateException,必須重新 new。
執行緒規則。實例建立與 execute() 都必須在 UI 主執行緒進行,四個回調也都跑在主執行緒上。
已於 API 30 被棄用。AsyncTask 在新版 Android 中已標記為 deprecated。新專案建議改用 Kotlin 協程、WorkManager(適合可延後、需保證完成的工作)或 java.util.concurrent 搭配 LiveData。
Apache HttpClient 早已移除。範例中的 DefaultHttpClient 在 Android 6.0 之後已從平台移除,實作時請替換為 HttpURLConnection 或 OkHttp。
記得處理旋轉。螢幕旋轉會重建 Activity,正在執行的任務此時回調 UI 會找不到目標。實務上建議把任務放在 ViewModel 或改用短生命週期的元件。
理解 AsyncTask 的執行模型之後,再去看協程或 RxJava 會輕鬆很多,因為核心問題是同一個:如何把背景計算的結果安全地送回主執行緒。
Android 中使用 JPush 自定義通知欄的實務指南
JPush 整合前的準備 在 Android 專案中使用 JPush 前,通常需要先完成 SDK 整合、appkey 設定與網路權限配置。若需要自定義通知欄,還要額外處理
Android 拍照與相冊照片裁剪實作
從相冊選擇照片並裁剪若需要讓使用者從相冊挑選圖片,並在選取後進行裁剪,可使用 ACTION_PICK,並將 type 設定為 image/*。接著透過 Intent 的
將 Eclipse 專案遷移到 Android Studio 的方法(圖文最新版)
前言近來 Android Studio(以下簡稱 AS)推出了正式版,火得不行。主要還是因為 Android 是 Google 自家的產品,AS 也是它自己搞的 IDE,
Android 網路流量控制入門:Iptables 防火牆機制解析
Iptables 的核心定位 Iptables 是 Linux 2.6 內核中常見的封包過濾工具,常用於防火牆、流量控制與網路安全策略。當 Android 裝置或伺服器需