异步任务-AsyncTack基本使用

2024-08-30 01:32

本文主要是介绍异步任务-AsyncTack基本使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

AsyncTask的基本使用方法

  在Day25我们讲解了Handler, 可以实现子线程数据传递到主线程(UI线程) 中去, 这样可以解决一些网络下载, 文件传输等需要子线程的完成的工作, 但是它也有一个小瑕疵 , 就是封装性不够好, 那就今天我们就要来说一下AsyncTask

介绍一下如何使用

1, 继承AsyncTask

public class MyTask extends AsyncTask<Params, Progrss, Result> 

我们来说一下这三个泛型的作用:

Params: 调用异步任务时传入的类型 ;

Progress : 字面意思上说是进度条, 实际上就是动态的由子线程向主线程publish数据的类型

Result : 返回结果的类型

2, 重写这个类的抽象方法doInBackground, 当然它也有几个方法需要重写, 我们一一看来

doInBackground(抽象方法, 必须实现)


/* 唯一执行在子线程中的方法*   所以不可以进行UI的更新* @param params* @return*/
@Override//返回值: Result       参数: Param
protected String doInBackground(TextView... params) {text = params[0];Random random = new Random();for (int i = 0; i < 50; i++) {//要进行进度的更新publishProgress(i);//不能直接调用onProgressUpdate方法,//这样会使得onProgressUpdate在子线程中运行try {Thread.sleep(random.nextInt(10) * 10);} catch (InterruptedException e) {e.printStackTrace();}}return "已完成";
}

下面三个方法根据具体情况选择使用

   //执行doInBackground之前调用@Overrideprotected void onPreExecute() {super.onPreExecute();}
    @Override//与publishProgress(i)对应protected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);text.setText(String.valueOf(values[0]));}
 //在doInBackground之后执行@Override // 参数s为 Resultprotected void onPostExecute(String s) {super.onPostExecute(s);text.setText(s);}

3, 执行异步任务

有两种方式, 我已经把区别写在了注释中

/*直接execute异步任务, 都是同一线程去执行
*/text = (TextView) findViewById(R.id.main_text1);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text2);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text3);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text4);
new MyTask().execute(text);
/*启动多条线程来执行异步任务API11以上可以使用
*/ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4);text = (TextView) findViewById(R.id.main_text1);new MyTask().executeOnExecutor(executor, text);text = (TextView) findViewById(R.id.main_text2);new MyTask().executeOnExecutor(executor, text);text = (TextView) findViewById(R.id.main_text3);new MyTask().executeOnExecutor(executor, text);text = (TextView) findViewById(R.id.main_text4);new MyTask().executeOnExecutor(executor, text);

注意: 如果我们直接去execute我们的任务, 它(任务) 只会在同一个子线程中运行, 所以上述第一种方式启动时, 四个任务顺次执行(就是一个任务执行完了再执行另一个); 而第二种方式, 给它创建了线程池, 这样会自动给它创建新的子线程, 所有的任务不是顺序执行, 而是几个线程”同时执行”

获取网络数据呈现在Webview和下载图片和其共存的案例

1, 首先我们要来一个布局, 具体需求是这样的, 在WebView之上有个ImageView, 并且, ImageView可以随WebView滚动, 所以这个时候我们想到了用ScrollView, 但是大家一定不要忘记, ScrollView只能包含一个控件, 所以我们可以用LinearLayout包裹一下即可

<ScrollView
    android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayout
        android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><ImageView
            android:id="@+id/main2_image"android:layout_width="wrap_content"android:layout_height="wrap_content" /><WebView
            android:id="@+id/main2_web"android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout>
</ScrollView>

2, 接下来我们要有一个实体类, 用来存放从网页上下载的内容(这里加注解原因在于我们要使用GSON解析来自网页的内容)

public class Entry {@SerializedName("title")private String title;@SerializedName("message")private String message;@SerializedName("img")private String image;public String getTitle() {return title;}...//省略其余getter和setter方法public void setImage(String image) {this.image = image;}
}

3, 那我们接下解决的问题就是 如何下载图片? 如何下载web内容? , 那我们写两个通用的工具类

下载工具类(通用型)

/*** Created by Lulu on 2016/8/31.* <p/>* 通用下载工具类*/
public class NetWorkTask<T> extends AsyncTask<NetWorkTask.Callback<T>, Void, Object> {private NetWorkTask.Callback<T> callback;private Class<T> t;private String url;public NetWorkTask(String url, Class<T> t) {this.url = url;this.t = t;}@Overrideprotected Object doInBackground(Callback<T>... params) {callback = params[0];try {HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();connection.setRequestMethod("GET");connection.setDoInput(true);int code = connection.getResponseCode();if (code == 200) {InputStream is = connection.getInputStream();ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[102400];int length;while ((length = is.read(buffer)) != -1) {bos.write(buffer, 0, length);}return bos.toString("UTF-8");} else {return  new RuntimeException("服务器异常");}} catch (Exception e) {e.printStackTrace();return e;}}@Overrideprotected void onPostExecute(Object o) {super.onPostExecute(o);if(o instanceof String) {String str = (String) o;Gson gson = new Gson();T t = gson.fromJson(str, this.t);callback.onSuccess(t);}if( o instanceof Exception) {Exception e = (Exception) o;callback.onFailed(e);}}public interface Callback<S> {void onSuccess(S t);void onFailed(Exception e);}
}

图片加载器(通用型)


/*** Created by Lulu on 2016/8/31.* 图片网络加载器* 下载成功返回Bitmap* 否则返回null*/
public class ImageLoader extends AsyncTask<String, Void, Bitmap>{private ImageView image;public ImageLoader(ImageView image) {this.image = image;image.setImageResource(R.mipmap.ic_launcher);}@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected Bitmap doInBackground(String... params) {String url = params[0];try {HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();connection.setRequestMethod("GET");connection.setDoInput(true);int code = connection.getResponseCode();if (code == 200) {InputStream is = connection.getInputStream();return BitmapFactory.decodeStream(is);}} catch (IOException e) {e.printStackTrace();}return null;}@Overrideprotected void onPostExecute(Bitmap bitmap) {super.onPostExecute(bitmap);if (bitmap != null) {image.setImageBitmap(bitmap);} else {image.setImageResource(R.mipmap.failed);}}
}

4, 测试Activity

注意: 看如何解决大图在webView中不左右滑动的问题!

public class Main2Activity extends AppCompatActivity implements NetWorkTask.Callback<Entry>{private WebView web;private ImageView image;//解决大图在webView中不左右滑动的问题private static final String CSS = "<style>img{max-width:100%} </style>";private String title;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);web = (WebView) findViewById(R.id.main2_web);image = (ImageView) findViewById(R.id.main2_image);new NetWorkTask<>("http://www.tngou.net/api/top/show?id=13122", Entry.class).execute(this);}@Overridepublic void onSuccess(Entry t) {web.loadDataWithBaseURL("", t.getMessage(), "text/html; charset=utf-8", "UTF-8", null);new ImageLoader(image).execute("https://img-blog.csdn.net/20160829134937003");}@Overridepublic void onFailed(Exception e) {web.loadDataWithBaseURL("", "加载失败", "text/html; charset=utf-8", "UTF-8", null);}
}

5, 效果图:

这里写图片描述

这篇关于异步任务-AsyncTack基本使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1119418

相关文章

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

SQL BETWEEN 语句的基本用法详解

《SQLBETWEEN语句的基本用法详解》SQLBETWEEN语句是一个用于在SQL查询中指定查询条件的重要工具,它允许用户指定一个范围,用于筛选符合特定条件的记录,本文将详细介绍BETWEEN语... 目录概述BETWEEN 语句的基本用法BETWEEN 语句的示例示例 1:查询年龄在 20 到 30 岁

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

mysql中insert into的基本用法和一些示例

《mysql中insertinto的基本用法和一些示例》INSERTINTO用于向MySQL表插入新行,支持单行/多行及部分列插入,下面给大家介绍mysql中insertinto的基本用法和一些示例... 目录基本语法插入单行数据插入多行数据插入部分列的数据插入默认值注意事项在mysql中,INSERT I

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ