編輯:關於 Android 程式設計
開發 Android 應用時必須遵守單線程模型:Android 的 UI 操作並非線程安全,且這些操作都必須在 UI 線程中執行。在單線程模型中要牢記兩條法則:
1. 不要阻塞 UI 線程。
2. 確保只在 UI 線程中訪問 Android UI 工具包。
程式第一次啟動時,Android 會啟動一個主線程(Main Thread),負責處理與 UI 相關的事件(如按鍵、觸控、繪圖)並分發給對應元件,因此主線程又稱 UI 線程。例如從網路抓取網頁並顯示到 TextView,這種涉及網络的操作必須另開線程,但在背景線程中不能直接呼叫 TextView.setText(),因為其他線程無法直接訪問 UI 線程的成員。
為了解決這個問題,Android 1.5 提供了工具類別 AsyncTask,讓需要與使用者介面互動的長時間任務變得更簡單。它相對輕量,適合簡單的異步處理,不需另外借助線程與 Handler。AsyncTask 是抽象類別,定義了三種泛型:Params(啟動任務的輸入參數,如 HTTP 請求的 URL)、Progress(後台任務執行的百分比)、Result(後台任務的最終回傳結果,如 String)。
1)子類化 AsyncTask。
2)實作以下一個或多個方法(不可由應用程式主動呼叫):
onPreExecute():在執行實際後台操作前由 UI 線程呼叫,可做準備工作,例如在介面顯示進度條。
doInBackground(Params...):在 onPreExecute 之後執行,運行於後台線程,負責耗時的計算工作,可呼叫 publishProgress() 更新進度;這是抽象方法,子類必須實作。
onProgressUpdate(Progress...):在 publishProgress 被呼叫後由 UI 線程觸發,用以在介面展示進展。
onPostExecute(Result):在 doInBackground 完成後由 UI 線程呼叫,把結果傳回 UI 線程。
1)Task 的實例必須在 UI 線程中建立。
2)execute 方法必須在 UI 線程中呼叫。
3)不要手動呼叫 onPreExecute、onPostExecute、doInBackground、onProgressUpdate。
4)同一個 Task 只能執行一次,否則會出現異常。
此外,doInBackground 與 onPostExecute 的參數需對應 AsyncTask 宣告的泛型:第一個是 doInBackground 的輸入參數、第二個是進度參數、第三個是 doInBackground 的回傳(也是 onPostExecute 的傳入)參數。
public class MainActivity extends Activity {
private Button button;
private ImageView imageview;
private String image_path = "https://d.hiphotos.baidu.com/image/w%3D2048/sign=72da8b71d62a60595210e61a1c0c369b/caef76094b36acaf0d08f1447dd98d1000e99c99.jpg";
private ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
dialog.setTitle("提示信息");
dialog.setMessage("正在下載,請稍等。。。。");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 橫向進度條
dialog.setCancelable(false); // 下載完成前不消失
button = (Button) this.findViewById(R.id.but);
imageview = (ImageView) this.findViewById(R.id.image);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
new MyTask().execute(image_path);
}
});
}
public class MyTask extends AsyncTask<String, Integer, Bitmap> {
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
inputStream = httpResponse.getEntity().getContent();
long file_length = httpResponse.getEntity().getContentLength(); // 檔案總長度
int len = 0;
byte[] data = new byte[1024];
int total_length = 0;
while ((len = inputStream.read(data)) != -1) {
total_length += len;
int value = (int) ((total_length / (float) file_length) * 100);
publishProgress(value); // 發布進度
outputStream.write(data, 0, len);
}
byte[] result = outputStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
dialog.dismiss();
imageview.setImageBitmap(result);
}
}
}
這個範例完整示範了 AsyncTask 的用法:在 doInBackground 中下載圖片並透過 publishProgress 回報進度,再由 onPostExecute 把結果設定到 ImageView,全程不必手動管理線程與 Handler。
自定義 Android EditText 背景與輸入驗證
用 layer-list 建立背景EditText 的背景可以透過 layer-list 與 shape 定義。使用 solid 設定填充色,stroke 設定邊框,co
Android 仿微信群聊頭像:多張頭像拼合實作
工作中有個需求,要實現類似釘釘群頭像那樣、把多張個人頭像拼在一起顯示的效果。研究了市面上幾款 App 後發現,微信群聊的頭像是採用組合方式呈現,而 QQ 則不是,其他 A
Android 自定義 View 實現縱向跑馬燈效果詳解
先來看看效果圖(錄製的 gif 有點卡,真機上是很流暢的) 實現思路 仔細看這段 gif 就能得出結論:本質上就是同時繪製上下兩條文本,然後用動畫持續改變它們距離頂部的
Android 獲取正在運行的應用並結束背景程式
取得正在運行的應用列表 在 Android 中,可以透過 ActivityManager 取得目前正在運行的應用程式列表。常見做法是呼叫 getRunningAppPro