Android 消息异步处理之AsyncTask
Android提供了异步处理消息的方式大致有两种,第一种是handler+Thread,之前已经对于这种方式做过分析,第二种就是AsyncTask,这是Android1.5提供的一种轻量级的工具类,其本质也是对handler和Thread进行了封装适用于一些简单的异步处理。
AsyncTask是一个抽象类,我们需要继承他并实现他的方法,其中有4个方法比较重要,对应着异步处理的几个过程。分别是:
onPreExecute()
- doInBackground(Params... var1)
- onProgressUpdate(Progress... values)
protected void onPostExecute(Result result)
这四个方法的一些参数和返回值都是基于泛型的,而且泛型的类型还不一样,所以在AsyncTask的使用中会遇到三种泛型参数:Params, Progress 和 Result。
- Params表示用于AsyncTask执行任务的参数的类型
- Progress表示在后台线程处理的过程中,可以阶段性地发布结果的数据类型
- Result表示任务全部完成后所返回的数据类型
我们通过调用asynctask的excute()方法就可以执行异步任务,会按照如上的顺序执行,下面依次来介绍一下这几个方法。
onPreExecute()
在执行任务之前在UI线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。
doInBackground(Params... var1)
在onPreExecute()完成执行后立即在后台线程上调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数将传递给此步骤。计算结果必须由此步骤返回,并将传递回最后一步。此步骤还可用于publishProgress(Progress...)发布一个或多个进度单位。这些值在onProgressUpdate(Progress...)步骤中发布在UI线程上 。
onProgressUpdate(Progress... values)
在调用后在UI线程上调用publishProgress(Progress...)。执行的时间是不确定的,如果在doInBackground中多次调用了publishProgress方法,那么主线程就会多次回调onProgressUpdate方法。此方法用于在后台计算仍在执行时显示用户界面中的任何形式的进度。例如,它可用于为进度条设置动画或在文本字段中显示日志。
protected void onPostExecute(Result result)
在后台计算完成后在UI线程上调用。doInBackground计算的结果作为参数传递给该步骤。
下面通过一个小demo来实现一下:
package com.hxc.supreme.activity; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView; import com.hxc.supreme.R;
import com.hxc.supreme.fragment.QuickControlFragment; import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; /**
* created by huxc on 2017/9/28.
* func:asynctask异步下载
* email: hxc242313@qq.com
*/ public class AsyncTaskActivity extends AppCompatActivity implements View.OnClickListener { private Button btnDownload;
private ImageView ivImage;
private TextView tvProgress;
private final String url = "http://i10.hoopchina.com.cn/hupuapp/bbs/741/36556741/thread_4847_36556741_20180619162627_83601.jpg?x-oss-process=image/resize,w_800/format,jpg"; @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_asynctask);
initView();
initListener();
initData();
} protected void initView() {
btnDownload = (Button) findViewById(R.id.btn_download);
ivImage = (ImageView) findViewById(R.id.iv_image);
tvProgress = (TextView) findViewById(R.id.tv_progress);
} protected void initListener() {
btnDownload.setOnClickListener(this);
} protected void initData() { } @Override
public void onClick(View view) {
if (view == btnDownload) {
MyAsyncTask asyncTask = new MyAsyncTask();
asyncTask.execute(url);
}
} class MyAsyncTask extends AsyncTask<String, String, Bitmap> { @Override
protected void onPreExecute() {
super.onPreExecute();
tvProgress.setText("下载开始");
} @Override
protected Bitmap doInBackground(String... strings) {
publishProgress("正在下载中...");
return getBitmapFromUrl(strings[0]);
} @Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
tvProgress.setText("正在下载中...");
} @Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
ivImage.setImageBitmap(bitmap);
tvProgress.setText("下载结束");
}
} public Bitmap getBitmapFromUrl(String urlString) {
Bitmap bitmap;
InputStream is = null; try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
connection.disconnect();
return bitmap; } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} }
布局也很简单就一个button、imageview、TextView
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"> <ImageView
android:id="@+id/iv_image"
android:layout_width="300dp"
android:layout_height="400dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" /> <TextView
android:id="@+id/tv_pro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="当前下载进度:"
app:layout_constraintLeft_toLeftOf="@+id/iv_image"
app:layout_constraintTop_toBottomOf="@+id/iv_image" /> <TextView
android:id="@+id/tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
app:layout_constraintLeft_toRightOf="@+id/tv_pro"
app:layout_constraintTop_toTopOf="@+id/tv_pro" /> <Button
android:id="@+id/btn_download"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="20dp"
android:background="@drawable/shape_config_btn_bg"
android:text="开始下载"
app:layout_constraintBottom_toBottomOf="parent" /> </android.support.constraint.ConstraintLayout>
最终的效果图就上我们可爱的刘人语小姐姐吧:

Android 消息异步处理之AsyncTask的更多相关文章
- Android:异步处理之AsyncTask的应用(二)
前言 在上一篇文章中<Android:异步处理之Handler+Thread的应用(一)>,我们知道Android的UI主线程主要负责处理用户的按键事件.用户的触屏事件以及屏幕绘图事件等: ...
- Android基本功:异步任务(AsyncTask)
一.解决新线程无法更新UI组建问题的方案 为了解决新线程不能更新UI组建的问题,Andorid提供了如下几种解决方案: 使用Handler实现线程之间的通信. Activity.runOnUiThre ...
- [转]Android:异步处理之AsyncTask的应用(二)
2014-11-07 既然UI老人家都这么忙了,我们这些开发者肯定不能不识趣的去添乱阻塞UI线程什么的,否则UI界面万一停止响应了呢——这不是招骂的节奏么?!所以我们知道用Handler+Th ...
- Android多线程异步处理:AsyncTask 的实现原理
AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法.注意继承时需要设定三个泛型P ...
- Android 之异步任务(AsyncTask,Handler,Message,looper)
AsyncTask: 3个类型(Params,Progress和Result),4个步骤(onPreExecute(),doInBackground(Params…),onProgressUpdate ...
- Java基础知识强化之网络编程笔记15:Android网络通信之 Android异步任务处理(AsyncTask使用)
AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的 ...
- Win32窗口消息机制 x Android消息机制 x 异步执行
如果你开发过Win32窗口程序,那么当你看到android代码到处都有的mHandler.sendEmptyMessage和 private final Handler mHandler = new ...
- Android - 消息机制与线程通信
以下资料摘录整理自老罗的Android之旅博客,是对老罗的博客关于Android底层原理的一个抽象的知识概括总结(如有错误欢迎指出)(侵删):http://blog.csdn.net/luosheng ...
- Android:异步处理之Handler、Looper、MessageQueue之间的恩怨(三)
前言 如果你在阅读本文之前,你不知道Handler在Android中为何物,我建议你先看看本系列的第一篇博文<Android:异步处理之Handler+Thread的应用(一)>:我们都知 ...
随机推荐
- golang IO streaming
IO Streaming Streaming IO in Go,引用此文,略有修改 io.Reader和io.Writer io.Reader接口定义了从传输缓存读取数据 type Reader in ...
- 3-7 Vue中的列表渲染
举个案例:循环data中的list的值在div中,并显示相应的index值. 关于数组的循环: //显示效果如下图: //一般的列表渲染最好带一个key值,要把key值设置为唯一值的话,可以选择in ...
- poj 1177 --- Picture(线段树+扫描线 求矩形并的周长)
题目链接 Description A number of rectangular posters, photographs and other pictures of the same shape a ...
- 【shiro】(5)---基于Shiro的权限管理
基于Shiro的权限管理项目搭建 前面写了四篇有关权限的文章,算是这篇文章的铺垫了.这篇文章采用 开发环境 JDK1.8 Eclipse Mav ...
- JavaScript和Ajax部分(3)
21. 原生(native)Ajax使用实例 //创建XMLHttpRequest对象的方法 function createXmlHttpRequest(){ if(window.ActiveXObj ...
- Socket网络编程基本介绍
一,socket的起源 socket一词的起源 在组网领域的首次使用是在1970年2月12日发布的文献IETF RFC33中发现的, 撰写者为Stephen Carr.Steve Crocker和Vi ...
- 第一册:lesson twentynine..
原文:Come in ,Amy. A:Come in B. Shut the door,please. This bedroom's very untidy. B:What must I do Mrs ...
- 从零开始学安全(十六)● Linux vim命令
游标控制 h 游标向左移 j 游标向下移 k 游标向上移 l (or spacebar) 游标向右移 w 向前移动一个单词 b 向后移动一个单词 e 向前移动一个单词,且游标指向单词的末尾 ( 移到当 ...
- T-SQL :SQL Server系统数据库(二)
master:master数据库储存实例范围的元数据信息,服务器配置,实例中的所有数据库信息和初始化信息. Resource:Resource数据库是一个隐藏,只读数据库,存储所有系统对象的定义.当查 ...
- win10下安装PHP_CodeSniffer 检查编码规范
PHP CodeSniffer是PEAR中的一个用PHP5写的一个PHP的代码风格检测器,它根据预先设定好的PHP编码风格和规则,去检查应用中的代码风格情况是否有违反一组预先设置好的编码标准,内置了Z ...