Android中AsyncTask異步任務(wù)使用詳細實例(一)
AsyncTask是Android提供的輕量級的異步類,可以直接繼承AsyncTask,在類中實現(xiàn)異步操作,并提供接口反饋當(dāng)前異步執(zhí)行的程度(可以通過接口實現(xiàn)UI進度更新),最后反饋執(zhí)行的結(jié)果給UI主線程。
使用AsyncTask最少要重寫以下兩個方法:
1、doInBackground(Params…) 后臺執(zhí)行,比較耗時的操作都可以放在這里。注意這里不能直接操作UI。此方法在后臺線程執(zhí)行,完成任務(wù)的主要工作,通常需要較長的時間。在執(zhí)行過程中可以調(diào)用publicProgress(Progress…)來更新任務(wù)的進度。
2、onPostExecute(Result) 在這里面可以使用在doInBackground 得到的結(jié)果處理操作UI。 此方法在主線程執(zhí)行,任務(wù)執(zhí)行的結(jié)果作為此方法的參數(shù)返回 。
MainActivity如下:
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一個實例,新建的任務(wù)只能執(zhí)行一次,否則會出現(xiàn)異常
//2 異步任務(wù)的實例必須在UI線程中創(chuàng)建
//3 execute()方法必須在UI線程中調(diào)用。
downLoaderAsyncTask=new DownLoaderAsyncTask();
downLoaderAsyncTask.execute("http://www.baidu.com");
break;
case R.id.cancelButton:
//取消一個正在執(zhí)行的任務(wù),onCancelled()方法將會被調(diào)用
downLoaderAsyncTask.cancel(true);
break;
default:
break;
}
}
}
//構(gòu)造函數(shù)AsyncTask<Params, Progress, Result>參數(shù)說明:
//Params 啟動任務(wù)執(zhí)行的輸入?yún)?shù)
//Progress 后臺任務(wù)執(zhí)行的進度
//Result 后臺計算結(jié)果的類型
private class DownLoaderAsyncTask extends AsyncTask<String, Integer, String>{
//onPreExecute()方法用于在執(zhí)行異步任務(wù)前,主線程做一些準(zhǔn)備工作
@Override
protected void onPreExecute() {
super.onPreExecute();
textView.setText("調(diào)用onPreExecute()方法--->準(zhǔn)備開始執(zhí)行異步任務(wù)");
System.out.println("調(diào)用onPreExecute()方法--->準(zhǔn)備開始執(zhí)行異步任務(wù)");
}
//doInBackground()方法用于在執(zhí)行異步任務(wù),不可以更改主線程中UI
@Override
protected String doInBackground(String... params) {
System.out.println("調(diào)用doInBackground()方法--->開始執(zhí)行異步任務(wù)");
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;
//publishProgress()為AsyncTask類中的方法
//常在doInBackground()中調(diào)用此方法
//用于通知主線程,后臺任務(wù)的執(zhí)行情況.
//此時會觸發(fā)AsyncTask中的onProgressUpdate()方法
publishProgress((int) ((count / (float) total) * 100));
//為了演示進度,休眠1000毫秒
Thread.sleep(1000);
}
return new String(bos.toByteArray(), "UTF-8");
}
} catch (Exception e) {
return null;
}
return null;
}
//onPostExecute()方法用于異步任務(wù)執(zhí)行完成后,在主線程中執(zhí)行的操作
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "調(diào)用onPostExecute()方法--->異步任務(wù)執(zhí)行完畢", 0).show();
//textView顯示網(wǎng)絡(luò)請求結(jié)果
textView.setText(result);
System.out.println("調(diào)用onPostExecute()方法--->異步任務(wù)執(zhí)行完畢");
}
//onProgressUpdate()方法用于更新異步執(zhí)行中,在主線程中處理異步任務(wù)的執(zhí)行信息
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//更改進度條
progressBar.setProgress(values[0]);
//更改TextView
textView.setText("已經(jīng)加載"+values[0]+"%");
}
//onCancelled()方法用于異步任務(wù)被取消時,在主線程中執(zhí)行相關(guān)的操作
@Override
protected void onCancelled() {
super.onCancelled();
//更改進度條進度為0
progressBar.setProgress(0);
//更改TextView
textView.setText("調(diào)用onCancelled()方法--->異步任務(wù)被取消");
System.out.println("調(diào)用onCancelled()方法--->異步任務(wù)被取消");
}
}
}
main.xml如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://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="開始異步任務(wù)" /> <Button android:id="@+id/cancelButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="取消異步任務(wù)" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" 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>
以上內(nèi)容是小編給大家介紹的Android中AsyncTask異步任務(wù)使用詳細實例(一),希望對大家有所幫助!
- android教程之使用asynctask在后臺運行耗時任務(wù)
- Android帶進度條的文件上傳示例(使用AsyncTask異步任務(wù))
- Android中使用AsyncTask實現(xiàn)文件下載以及進度更新提示
- Android 中使用 AsyncTask 異步讀取網(wǎng)絡(luò)圖片
- Android中使用AsyncTask實現(xiàn)下載文件動態(tài)更新進度條功能
- Android使用AsyncTask下載圖片并顯示進度條功能
- 詳解Android中AsyncTask的使用方法
- Android使用AsyncTask實現(xiàn)多線程下載的方法
- Android AsyncTask詳解及使用方法
- Android中AsyncTask的入門使用學(xué)習(xí)指南
相關(guān)文章
Android開發(fā)Jetpack組件LiveData使用講解
LiveData是Jetpack組件的一部分,更多的時候是搭配ViewModel來使用,相對于Observable,LiveData的最大優(yōu)勢是其具有生命感知的,換句話說,LiveData可以保證只有在組件( Activity、Fragment、Service)處于活動生命周期狀態(tài)的時候才會更新數(shù)據(jù)2022-08-08
Android library native調(diào)試代碼遇到的問題解決
這篇文章主要介紹了Android library native 代碼不能調(diào)試解決方法匯總,android native開發(fā)會碰到native代碼無法調(diào)試問題,而app主工程中的native代碼是可以調(diào)試的2023-04-04
Android ScrollView實現(xiàn)向上滑動控件頂部懸浮效果
這篇文章主要為大家詳細介紹了Android ScrollView實現(xiàn)向上滑動控件頂部懸浮效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
Android性能優(yōu)化之利用Rxlifecycle解決RxJava內(nèi)存泄漏詳解
RxJava作為一種響應(yīng)式編程框架,是目前編程界網(wǎng)紅,可謂是家喻戶曉,其簡潔的編碼風(fēng)格、易用易讀的鏈?zhǔn)椒椒ㄕ{(diào)用、強大的異步支持等使得RxJava被廣泛使用。2017-01-01
Android 加載大圖及多圖避免程序出現(xiàn)OOM(OutOfMemory)異常
這篇文章主要介紹了Android 加載大圖及多圖避免程序出現(xiàn)OOM(OutOfMemory)異常的相關(guān)資料,需要的朋友可以參考下2017-03-03

