Android中AsyncTask異步任務(wù)使用詳細(xì)實(shí)例(一)
AsyncTask是Android提供的輕量級(jí)的異步類,可以直接繼承AsyncTask,在類中實(shí)現(xiàn)異步操作,并提供接口反饋當(dāng)前異步執(zhí)行的程度(可以通過接口實(shí)現(xiàn)UI進(jìn)度更新),最后反饋執(zhí)行的結(jié)果給UI主線程。
使用AsyncTask最少要重寫以下兩個(gè)方法:
1、doInBackground(Params…) 后臺(tái)執(zhí)行,比較耗時(shí)的操作都可以放在這里。注意這里不能直接操作UI。此方法在后臺(tái)線程執(zhí)行,完成任務(wù)的主要工作,通常需要較長(zhǎng)的時(shí)間。在執(zhí)行過程中可以調(diào)用publicProgress(Progress…)來更新任務(wù)的進(jìn)度。
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一個(gè)實(shí)例,新建的任務(wù)只能執(zhí)行一次,否則會(huì)出現(xiàn)異常 //2 異步任務(wù)的實(shí)例必須在UI線程中創(chuàng)建 //3 execute()方法必須在UI線程中調(diào)用。 downLoaderAsyncTask=new DownLoaderAsyncTask(); downLoaderAsyncTask.execute("http://www.baidu.com"); break; case R.id.cancelButton: //取消一個(gè)正在執(zhí)行的任務(wù),onCancelled()方法將會(huì)被調(diào)用 downLoaderAsyncTask.cancel(true); break; default: break; } } } //構(gòu)造函數(shù)AsyncTask<Params, Progress, Result>參數(shù)說明: //Params 啟動(dòng)任務(wù)執(zhí)行的輸入?yún)?shù) //Progress 后臺(tái)任務(wù)執(zhí)行的進(jìn)度 //Result 后臺(tái)計(jì)算結(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)用此方法 //用于通知主線程,后臺(tái)任務(wù)的執(zhí)行情況. //此時(shí)會(huì)觸發(fā)AsyncTask中的onProgressUpdate()方法 publishProgress((int) ((count / (float) total) * 100)); //為了演示進(jìn)度,休眠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ò)請(qǐng)求結(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); //更改進(jìn)度條 progressBar.setProgress(values[0]); //更改TextView textView.setText("已經(jīng)加載"+values[0]+"%"); } //onCancelled()方法用于異步任務(wù)被取消時(shí),在主線程中執(zhí)行相關(guān)的操作 @Override protected void onCancelled() { super.onCancelled(); //更改進(jìn)度條進(jìn)度為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ù)使用詳細(xì)實(shí)例(一),希望對(duì)大家有所幫助!
- android教程之使用asynctask在后臺(tái)運(yùn)行耗時(shí)任務(wù)
- Android帶進(jìn)度條的文件上傳示例(使用AsyncTask異步任務(wù))
- Android中使用AsyncTask實(shí)現(xiàn)文件下載以及進(jìn)度更新提示
- Android 中使用 AsyncTask 異步讀取網(wǎng)絡(luò)圖片
- Android中使用AsyncTask實(shí)現(xiàn)下載文件動(dòng)態(tài)更新進(jìn)度條功能
- Android使用AsyncTask下載圖片并顯示進(jìn)度條功能
- 詳解Android中AsyncTask的使用方法
- Android使用AsyncTask實(shí)現(xiàn)多線程下載的方法
- Android AsyncTask詳解及使用方法
- Android中AsyncTask的入門使用學(xué)習(xí)指南
相關(guān)文章
詳談Android中Matrix的set、pre、post的區(qū)別
下面小編就為大家?guī)硪黄斦凙ndroid中Matrix的set、pre、post的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04Android下拉刷新完全解析,教你如何一分鐘實(shí)現(xiàn)下拉刷新功能(附源碼)
以下是我自己花功夫編寫了一種非常簡(jiǎn)單的下拉刷新實(shí)現(xiàn)方案,現(xiàn)在拿出來和大家分享一下。相信在閱讀完本篇文章之后,大家都可以在自己的項(xiàng)目中一分鐘引入下拉刷新功能2013-07-07如何在Android中實(shí)現(xiàn)一個(gè)簡(jiǎn)易的Http服務(wù)器
這篇文章主要介紹了如何在Android中實(shí)現(xiàn)一個(gè)簡(jiǎn)易的Http服務(wù)器,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05Android布局——Preference自定義layout的方法
PreferenceActivity是一個(gè)方便設(shè)置管理的界面,但是對(duì)于界面顯示來說比較單調(diào),所以自定義布局就很有必要了,下面與大家分享下Preference中自定義layout的方法2013-06-06簡(jiǎn)單學(xué)習(xí)Android TextView
這篇文章主要和大家一起簡(jiǎn)單學(xué)習(xí)Android TextView,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09淺談Android系統(tǒng)的基本體系結(jié)構(gòu)與內(nèi)存管理優(yōu)化
這篇文章主要介紹了Android系統(tǒng)的基本體系結(jié)構(gòu)與內(nèi)存管理優(yōu)化,非常簡(jiǎn)潔明了地總結(jié)了系統(tǒng)服務(wù)及垃圾回收等安卓的一些主要特性,需要的朋友可以參考下2016-02-02Android實(shí)例代碼理解設(shè)計(jì)模式SOLID六大原則
程序設(shè)計(jì)領(lǐng)域, SOLID (單一功能、開閉原則、里氏替換、接口隔離以及依賴反轉(zhuǎn))是由羅伯特·C·馬丁在21世紀(jì)早期 引入的記憶術(shù)首字母縮略字,指代了面向?qū)ο缶幊毯兔嫦驅(qū)ο笤O(shè)計(jì)的基本原則2021-10-10Activity透明/半透明效果的設(shè)置transparent(兩種實(shí)現(xiàn)方法)
兩種方法實(shí)現(xiàn)Activity透明/半透明效果的設(shè)置,代碼思路很有調(diào)理,感興趣的朋友可以參考下,希望本文可以幫助到你2013-02-02