編輯:關於 Android 程式設計
AsyncTask 是 Android 封裝好的非同步機制,讓你能用很直觀的方式把耗時任務丟到背景執行緒,再安全地回到主執行緒更新 UI。
因為只有 UI 線程(主線程)能對控制項進行更新操作。這樣做的好處是保證 UI 穩定性,避免多執行緒同時操作介面造成不可預期的狀態。
反過來的代價是:任何耗時任務如果放在主線程執行,就會造成阻塞,最終拋出 ANR(Application Not Responding)。所以規則很簡單——耗時任務丟背景,結果回主線程。
AsyncTask 是抽象類,必須繼承後使用,形如 AsyncTask<Params, Progress, Result>:
publishProgress() 時被觸發,用來更新執行進度。後三個方法都在主執行緒中執行,所以能安全地碰 UI。
execute() 方法。另外還有一個容易忽略的限制:同一個 AsyncTask 實例只能執行一次。第二次呼叫 execute() 會拋出 IllegalStateException,必須重新 new 一個。
activity_main.xml:兩個入口按鈕
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="異步加載網絡圖片" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="模擬進度條" />
</LinearLayout>
activity_image.xml:ImageView + 初始隱藏的 ProgressBar
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="43dp"
android:text="加載圖片:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="24dp"
android:layout_marginTop="20dp" />
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:visibility="gone" />
</RelativeLayout>
activity_progressbar.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="16dp">
<ProgressBar
android:id="@+id/progressBar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="209dp" />
</RelativeLayout>
MainActivity.java
package com.example.asynctaskdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, LoadImageActivity.class);
MainActivity.this.finish();
startActivity(intent);
}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, ProgressBarActivity.class);
MainActivity.this.finish();
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.example.asynctaskdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class LoadImageActivity extends Activity {
private ProgressBar progressBar;
private ImageView imageView;
private String URL = "https://avatar.csdn.net/F/1/0/3_u012422829.jpg";
// 三個參數:String 是輸入的網址,Bitmap 是結果,
// Progress 不需要中途回報資訊,所以用 Void
class LoadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPreExecute() {
// 在主執行緒做初始化
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
// 開啟非同步執行緒執行操作
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
Bitmap bitmap = null;
InputStream is = null;
try {
// 先睡 3 秒,不然速度太快看不出效果
Thread.sleep(3000);
URLConnection urlConnection = new URL(url).openConnection();
is = urlConnection.getInputStream();
BufferedInputStream bfis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bfis);
bfis.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (is != null) {
try { is.close(); } catch (IOException e) { }
}
}
return bitmap; // return 給 onPostExecute 方法
}
@Override
protected void onPostExecute(Bitmap result) {
progressBar.setVisibility(View.GONE);
imageView.setImageBitmap(result);
super.onPostExecute(result);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
imageView = (ImageView) findViewById(R.id.imageView1);
// 在主執行緒中不能直接呼叫那四個覆寫的方法,只能呼叫 execute
// 系統會自動依序執行 onPreExecute → doInBackground → onPostExecute
new LoadImageAsyncTask().execute(URL);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
這裡我們定義了一個內部類 LoadImageAsyncTask 繼承自 AsyncTask,三個泛型參數的意義如註解所述。介面啟動時 new 一個物件並呼叫 execute(),把網址當參數傳給 doInBackground()。特別注意:不能呼叫覆寫的那四個方法,那是系統自動呼叫的。執行順序是 onPreExecute() 做初始化 → doInBackground() 抓圖 → 結果傳給 onPostExecute() 更新 UI。這個例子沒用到 onProgressUpdate(),下面的例子會示範。
package com.example.asynctaskdemo;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ProgressBar;
import android.widget.Toast;
public class ProgressBarActivity extends Activity {
private ProgressBar progressBar;
private ProgressAsyncTask progressAsyncTask;
class ProgressAsyncTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < 100; i++) {
publishProgress(i); // i 值傳遞給 onProgressUpdate
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]); // 更新進度
}
@Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "完成任務",
Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progressbar);
progressBar = (ProgressBar) findViewById(R.id.progressBar2);
progressAsyncTask = new ProgressAsyncTask();
progressAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
結構和上一個例子相同,差別在於第二個泛型參數改成了 Integer,讓 publishProgress() 能把目前進度傳給 onProgressUpdate(),在那裡直接 setProgress()。
AsyncTask 在 API 11 之後已被標記為不建議使用,官方推薦改用 ViewModel + LiveData 搭配 Kotlin 協程,或至少用 ExecutorService。AsyncTask 有幾個已知的問題:
onPostExecute() 更新 UI 時,Activity 已經銷毀,會造成記憶體洩漏或直接崩潰。Thread.sleep(3000) 只是為了看效果,實戰中不要這樣寫。
《Android 從入門到精通》閱讀筆記(29):四大 Layout 的常用方法速查
版面配置類別的方法實在太多,每次翻文件找都很耗時間。這篇把 LinearLayout、RelativeLayout、TableLayout 與 AbsoluteLayou
Android 元件工具箱(widget toolbox)速覽
Android SDK 本身就附了一套標準的元件工具箱,足以應付大多數初學與一般性的介面需求,不必急著引入第三方庫。以下依用途整理常用控制項。 文字類 TextVie
Android Studio 教程(三):常用快捷鍵
今天是個大日子,Android Studio 1.0 終於發布了正式版,對於 Android 開發者來說無疑是喜聞樂見的消息,那就果斷下載來用吧。 官方下載地址:htt
自定義 TextView:同時匹配表情、關鍵字與 Url 的超實用控件
注意:在 EditText 和 TextView 中,不要設置下面這兩個屬性中的任何一個,否則當文本超過一行後,會出現表情、圖片對不齊的情況。 android:lineS