AsyncTask详解 并实现实例-模拟下载

来源:互联网 发布:兴业证券软件优理宝 编辑:程序博客网 时间:2024/06/13 14:10

API中的内容:

简介

Class Overview

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask是更简单的UI线程实现方式。这个类允许后台操作,并允许发布结果到UI线程。而不需要去操作thread和handler
AsyncTask is designed to be a helper class around Thread and Handler

and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.


AsyncTask实现原理还是Thread和handler,不过谷歌包装好了(那就用呗)。

An asynchronous task is defined by a computation that runs on a background thread and

whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask的三个泛型分别对应的是Params, Progress and Result
还有四个步骤:见名思义吧

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
千万别忘了在主线程中执行!!!

Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

实例:模拟下载(练手加看个大概)

布局是这个样子的
<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"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="44"
/>

<Button
android:id="@+id/button_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始下载" />

</LinearLayout>
AsyncTask  实际上就是google帮我们封装好的线程UI同步类。通过过修饰handler和Thread类实现:代码如下
public class MainActivity extends AppCompatActivity {
    private Button mButtonDown;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonDown = (Button) findViewById(R.id.button_down);
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mButtonDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadFilesTask().execute();
}
});
}

private class DownloadFilesTask extends AsyncTask<String, String, String> {
private int count=0;

/**
* @param params execute()中传入的参数
* @return 传给onPostExecute的参数
* doInBackground不能与UI进行交互,但可以传递给onProgressUpdate,onPostExecute方法进行操作
*/
@Override
protected String doInBackground(String... params) {
while (count<101){
count++;
publishProgress(""+count);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "下载完成";
}

/**
* 在doInBackground结束时执行
* @param s
*/
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mButtonDown.setText(s);
}

/**
* 在doInBackground中使用publishProgress(""+count)给onProgressUpdate传递参数,进行UI的更新
* @param values
*/
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
int count = Integer.parseInt(values[0]);
mProgressBar.setProgress(count);
}
}
}



0 0
原创粉丝点击