侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Android AsyncTack 异步任务实例详解

php  /  管理员 发布于 7年前   287

Android AsyncTack 异步任务

              这里写一个小实例,来学习巩固Android AsyncTack 异步任务的知识,以便在项目中使用。

介绍一下如何使用

1, 继承AsyncTask

public class MyTask extends AsyncTask

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

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

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

Result : 返回结果的类型

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

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

/* 唯一执行在子线程中的方法 *  所以不可以进行UI的更新 * @param params * @return */@Override//返回值: Result    参数: Paramprotected 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之前调用  @Override  protected void onPreExecute() {    super.onPreExecute();  }
  @Override//与publishProgress(i)对应  protected void onProgressUpdate(Integer... values) {    super.onProgressUpdate(values);    text.setText(String.valueOf(values[0]));  }
 //在doInBackground之后执行  @Override // 参数s为 Result  protected 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包裹一下即可

            

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. * 

* 通用下载工具类 */public class NetWorkTask extends AsyncTask, Void, Object> { private NetWorkTask.Callback callback; private Class t; private String url; public NetWorkTask(String url, Class t) { this.url = url; this.t = t; } @Override protected Object doInBackground(Callback... 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; } } @Override protected 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 { void onSuccess(S t); void onFailed(Exception e); }}

图片加载器(通用型)

/** * Created by Lulu on 2016/8/31. * 图片网络加载器 * 下载成功返回Bitmap * 否则返回null */public class ImageLoader extends AsyncTask{  private ImageView image;  public ImageLoader(ImageView image) {    this.image = image;    image.setImageResource(R.mipmap.ic_launcher);  }  @Override  protected void onPreExecute() {    super.onPreExecute();  }  @Override  protected 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;  }  @Override  protected 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{  private WebView web;  private ImageView image;  //解决大图在webView中不左右滑动的问题  private static final String CSS = "";  private String title;  @Override  protected 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);  }  @Override  public void onSuccess(Entry t) {    web.loadDataWithBaseURL("", t.getMessage(), "text/html; ", "UTF-8", null);    new ImageLoader(image).execute("http://img.blog.csdn.net/20160829134937003");  }  @Override  public void onFailed(Exception e) {    web.loadDataWithBaseURL("", "加载失败", "text/html; charset=utf-8", "UTF-8", null);  }}

5.效果图:

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:

  • Android带进度条的文件上传示例(使用AsyncTask异步任务)
  • Android 中糟糕的AsyncTask
  • Android中通过AsyncTask类来制作炫酷进度条的实例教程
  • 详解Android App中的AsyncTask异步任务执行方式
  • Android使用AsyncTask实现多线程下载的方法
  • Android中AsyncTask异步任务使用详细实例(一)
  • Android 中使用 AsyncTask 异步读取网络图片
  • 详解Android中AsyncTask机制
  • Android通过Handler与AsyncTask两种方式动态更新ListView(附源码)
  • Android的异步任务AsyncTask详解


  • 上一条:
    支付宝支付开发――当面付条码支付和扫码支付实例
    下一条:
    遍历echsop的region表形成缓存的程序实例代码
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客