现在的位置: 首页 > 综合 > 正文

Android AsyncTask用法

2017年12月15日 ⁄ 综合 ⁄ 共 1691字 ⁄ 字号 评论关闭

AsyncTask 是一个轻量级的线程,允许你直接将线程里完成的事情更新到UI线程中,类似于Thread + Handler的方式,只不过,它封闭起来完成了,如果你要完成一些费时复杂的工作,还是建议不要采用这个方法,取而代之的是使用Thread, ThreadPool等方式来完成。

AsyncTask 有4个步骤:onPreExecute, doInBackground, onProgressUpdate and
onPostExecute,不过,它有3个可输入参数,这3个参数是可变参数,即个数可变,但类型一但确定,传过来的都必需是相同类型。

执行流程是:onPreExecute -> doInBackground -> onProgressUpdate ->
onPostExecute

public class MyTask extends AsyncTask<Params, Progress, Result> {

	@Override
	protected Result doInBackground(Params... arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void onProgressUpdate(Progress... progress) {

	}

	@Override
	protected void onPostExecute(Result result) {

	}
	
}

三个参数与以上三个函数的输入参数一一对应,不过,通常onProgressUpdate的参数都由doInBackground传过来,在doInBackground中,可以调用publishProgress,这样在onProgressUpdate中,就能够按照你的想法,在UI线程中更新显示。

Android 官方文档手册中,给出对这三个参数的解释:

The three types used by an asynchronous task are the following:
    1. Params, the type of the parameters sent to the task upon execution.
    2. Progress, the type of the progress units published during the background computation.

    3. Result, the type of the result of the background computation.

这三个参数的类型,可以是Integer, Long, String, Void等,在使用过程中,参数都以数组形式存于可变参数变量中。

举例:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

这是一个下载是,显示进度条的例子,调用方法为:new DownloadFilesTask().execute(url1, url2, url3);

简单吧! ^-^! 大家一但用熟了,就对它爱不释手了,不过,千万记住,它只是个轻量级的线程!

抱歉!评论已关闭.