AsyncTask详解 并实现实例-模拟下载
2015-09-09 22:31
309 查看
API中的内容:
简介
AsyncTask is designed to be a helper class aroundClass 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
Threadand
Handlerand 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.concurrentpackage such as
Executor,
ThreadPoolExecutorand
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,
Progressand
Result, and 4 steps, called
onPreExecute,
doInBackground,
onProgressUpdateand
onPostExecute.AsyncTask的三个泛型分别对应的是
Params,
Progressand
Result
还有四个步骤:见名思义吧
, 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.The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
[code]onPreExecute()
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.
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.
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);[/code]
实例:模拟下载(练手加看个大概)
布局是这个样子的
<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); } } }
相关文章推荐
- JavaScript之字符串对象
- 9月9日刷题
- 使用ANT编译项目报错 com.sun.image.codec.jpeg does not exist 解决方法
- 树的应用:排列和组合
- hdu 4857 逃生
- 对数据库中数据库系统的结构的认识
- json在javaScrit中如何正确使用
- Akka Acto官方文档笔记
- 项目风险管理
- Asp.Net 正则表达式的应用
- ios-播放器开发-锁屏、循环播放
- Android问题解决之空指针(null)
- uvalive 3907 Puzzle (ac自动机+有向图判环+dp)
- 《剑指Offer》面试题:丑数
- WCF基础之大型数据和流
- GO数组和切片
- Markdown语法学习(二)
- centOS6.5 heartbeatV3+pacemaker实现高可用集群
- 关于 CocoaPods的安装
- LinkedList的使用——控制台输出贪吃蛇游戏