android中AsyncTask和Handler对比

1 ) AsyncTask实现的原理,和适用的优缺点

AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程.

使用的优点:

l  简单,快捷

l  过程可控

       

使用的缺点:

l  在使用多个异步操作和并需要进行Ui变更时,就变得复杂起来.

2 )Handler异步实现的原理和适用的优缺点

在Handler 异步实现时,涉及到 Handler, Looper, Message,Thread四个对象,实现异步的流程是主线程启动Thread(子线程)àthread(子线程)运行并生成Message-àLooper获取Message并传递给HandleràHandler逐个获取Looper中的Message,并进行UI变更。

使用的优点:

l  结构清晰,功能定义明确

l  对于多个后台任务时,简单,清晰

   

使用的缺点:

l  在单个后台异步处理时,显得代码过多,结构过于复杂(相对性)

AsyncTask介绍
Android的AsyncTask比Handler更轻量级一些,适用于简单的异步处理。
首先明确Android之所以有Handler和AsyncTask,都是为了不阻塞主线程(UI线程),且UI的更新只能在主线程中完成,因此异步处理是不可避免的。

Android为了降低这个开发难度,提供了AsyncTask。AsyncTask就是一个封装过的后台任务类,顾名思义就是异步任务。

AsyncTask直接继承于Object类,位置为android.os.AsyncTask。要使用AsyncTask工作我们要提供三个泛型参数,并重载几个方法(至少重载一个)。

 

AsyncTask定义了三种泛型类型 Params,Progress和Result。

  • Params 启动任务执行的输入参数,比如HTTP请求的URL。
  • Progress 后台任务执行的百分比。
  • Result 后台执行任务最终返回的结果,比如String。

使用过AsyncTask 的同学都知道一个异步加载数据最少要重写以下这两个方法:

  • doInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
  • onPostExecute(Result)  相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行,任务执行的结果作为此方法的参数返回

有必要的话你还得重写以下这三个方法,但不是必须的:

  • onProgressUpdate(Progress…)   可以使用进度条增加用户体验度。 此方法在主线程执行,用于显示任务执行的进度。
  • onPreExecute()        这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,可以在这里显示进度对话框。
  • onCancelled()             用户调用取消时,要做的操作

使用AsyncTask类,以下是几条必须遵守的准则:

  • Task的实例必须在UI thread中创建;
  • execute方法必须在UI thread中调用;
  • 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法;
  • 该task只能被执行一次,否则多次调用时将会出现异常;

    一个超简单的理解 AsyncTask 的例子:

    main.xml

    [java] view plaincopy
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:orientation="vertical"  
    4.     android:layout_width="fill_parent"  
    5.     android:layout_height="fill_parent"  
    6.     >  
    7.     <TextView    
    8.     android:id="@+id/textView01"  
    9.     android:layout_width="fill_parent"   
    10.     android:layout_height="wrap_content"   
    11.     />  
    12.    <ProgressBar   
    13.    android:id="@+id/progressBar02"  
    14.     android:layout_width="fill_parent"   
    15.     android:layout_height="wrap_content"   
    16.     style="?android:attr/progressBarStyleHorizontal"   
    17.     />  
    18.     <Button  
    19.     android:id="@+id/button03"  
    20.     android:layout_width="fill_parent"   
    21.     android:layout_height="wrap_content"   
    22.     android:text="更新progressbar"  
    23.     />  
    24. </LinearLayout>  


    MainActivity.java

    [html] view plaincopy
    1. package vic.wong.main;  
    2.   
    3. import android.app.Activity;  
    4. import android.os.Bundle;  
    5. import android.view.View;  
    6. import android.view.View.OnClickListener;  
    7. import android.widget.Button;  
    8. import android.widget.ProgressBar;  
    9. import android.widget.TextView;  
    10.   
    11. public class MainActivity extends Activity {  
    12.     private Button button;  
    13.     private ProgressBar progressBar;  
    14.     private TextView textView;  
    15.       
    16.     @Override  
    17.     public void onCreate(Bundle savedInstanceState) {  
    18.         super.onCreate(savedInstanceState);  
    19.         setContentView(R.layout.main);  
    20.           
    21.         button = (Button)findViewById(R.id.button03);  
    22.         progressBar = (ProgressBar)findViewById(R.id.progressBar02);  
    23.         textView = (TextView)findViewById(R.id.textView01);  
    24.           
    25.         button.setOnClickListener(new OnClickListener() {  
    26.               
    27.             @Override  
    28.             public void onClick(View v) {  
    29.                 ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar);  
    30.                 asyncTask.execute(1000);  
    31.             }  
    32.         });  
    33.     }  
    34. }  

     


    NetOperator.java

    [html] view plaincopy
    1. package vic.wong.main;  
    2.   
    3.   
    4. //模拟网络环境  
    5. public class NetOperator {  
    6.       
    7.     public void operator(){  
    8.         try {  
    9.             //休眠1秒  
    10.             Thread.sleep(1000);  
    11.         } catch (InterruptedException e) {  
    12.             // TODO Auto-generated catch block  
    13.             e.printStackTrace();  
    14.         }  
    15.     }  
    16.   
    17. }  

     


    ProgressBarAsyncTask .java 

    [html] view plaincopy
    1. package vic.wong.main;  
    2. import android.os.AsyncTask;  
    3. import android.widget.ProgressBar;  
    4. import android.widget.TextView;  
    5.   
    6. /**  
    7.  * 生成该类的对象,并调用execute方法之后  
    8.  * 首先执行的是onProExecute方法  
    9.  * 其次执行doInBackgroup方法  
    10.  *  
    11.  */  
    12. public class ProgressBarAsyncTask extends AsyncTask<Integer, Integer, String> {  
    13.   
    14.     private TextView textView;  
    15.     private ProgressBar progressBar;  
    16.       
    17.       
    18.     public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) {  
    19.         super();  
    20.         this.textView = textView;  
    21.         this.progressBar = progressBar;  
    22.     }  
    23.   
    24.   
    25.     /**  
    26.      * 这里的Integer参数对应AsyncTask中的第一个参数   
    27.      * 这里的String返回值对应AsyncTask的第三个参数  
    28.      * 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改  
    29.      * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作  
    30.      */  
    31.     @Override  
    32.     protected String doInBackground(Integer... params) {  
    33.         NetOperator netOperator = new NetOperator();  
    34.         int i = 0;  
    35.         for (i = 10; i <= 100; i+=10) {  
    36.             netOperator.operator();  
    37.             publishProgress(i);  
    38.         }  
    39.         return i + params[0].intValue() + "";  
    40.     }  
    41.   
    42.   
    43.     /**  
    44.      * 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)  
    45.      * 在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI空间进行设置  
    46.      */  
    47.     @Override  
    48.     protected void onPostExecute(String result) {  
    49.         textView.setText("异步操作执行结束" + result);  
    50.     }  
    51.   
    52.   
    53.     //该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置  
    54.     @Override  
    55.     protected void onPreExecute() {  
    56.         textView.setText("开始执行异步线程");  
    57.     }  
    58.   
    59.   
    60.     /**  
    61.      * 这里的Intege参数对应AsyncTask中的第二个参数  
    62.      * 在doInBackground方法当中,,每次调用publishProgress方法都会触发onProgressUpdate执行  
    63.      * onProgressUpdate是在UI线程中执行,所有可以对UI空间进行操作  
    64.      */  
    65.     @Override  
    66.     protected void onProgressUpdate(Integer... values) {  
    67.         int vlaue = values[0];  
    68.         progressBar.setProgress(vlaue);  
    69.     }  
    70.   
    71.       
    72.       
    73.       
    74.   
    75. }  

转载于:https://www.cnblogs.com/wangluochong/archive/2013/03/04/2942247.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/274341.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

视觉工程师面试指南_选择正确视觉效果的终极指南

视觉工程师面试指南When it comes to effective data visualization, the very first and also the most critical step is to select the right graph/visual for the data that you want to present. With a wide range of visualization software that is available offerin…

在 Linux 下使用 水星MW150cus (RTL8188CUS芯片)无线网卡

Fedora &#xff08;如果你不使用 PAE 内核&#xff0c;请去掉 PAE 字样&#xff09;:yum install gcc kernel-PAE kernel-PAE-devel kernel-headers dkms Ubuntu: apt-get install make gcc linux-kernel-devel linux-headers-uname -r安装原生驱动 注意&#xff1a;由于在 Li…

问题反馈模板_使用此模板可获得更好,更有价值的UX反馈

问题反馈模板Feedback is an important part of UX design. To improve the work you do you need to be able to give and receive feedback. Receiving valuable feedback is for a very large part up to you.反馈是UX设计的重要组成部分。 为了改进您的工作&#xff0c;您需…

【转载】Android Animation 简介(官方文档翻译) ---- 翻译的很好!

http://vaero.blog.51cto.com/4350852/849783转载于:https://www.cnblogs.com/DonkeyTomy/articles/2945687.html

ubuntu 如何转换 ppk ,连接 amazon ec2

转 自 &#xff1a;http://www.ehow.com/how_8658327_convert-ppk-ssh-ubuntu.html1 Open a terminal window in Ubuntu, or log in if you are converting the keys on a remote Ubuntu server. 2 Type "sudo apt-get install putty-tools" at the terminal prompt …

iofd:文件描述符_文字很重要:谈论设计时18个有意义的描述符

iofd:文件描述符As designers, many of us think we’re just visual creatures. But creating visuals is only half of the job. The other half is verbal communication — actually talking about design. Whether we’re showcasing our own work, giving or receiving c…

保护程序猿滴眼睛-----修改VS 2008 编辑器颜色 (修改 chrome浏览器的背景色)

前几天更改了 chrome 的背景色后&#xff0c;虽然有些地方看起来不和谐&#xff0c;想百度的首页&#xff0c;显示出了大快的图片区域&#xff0c;但是&#xff0c;整体感觉这个颜色设置真的对眼睛有一定保护作用。。。 所以&#xff0c;再顺便修改一下 经常用的 vs2008 编辑器…

数据可视化 信息可视化_可视化哲学的黎明

数据可视化 信息可视化Note: this is the foreword of the book Data Visualization in Society (Amsterdam University Press, 2020)注意&#xff1a;这是《 社会中的数据可视化 》一书的前言 (阿姆斯特丹大学出版社&#xff0c;2020年) Geographer John Pickles once wrote …

HTTP 错误 404.2 - Not Found 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面...

详细错误&#xff1a;HTTP 错误 404.2 - Not Found. 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置&#xff0c;无法提供您请求的页面. 出现环境&#xff1a;win7 IIS7.0 解决办法&#xff1a;IIS的根节点->右侧“ISAPI和CGI限制”->把禁止的DotNet版本项设置为允许…

重口味动漫_每种口味的图标样式

重口味动漫The icons are, without a doubt, one of the most used graphic elements today in the interface design of digital products. And to make this statement with some degree of certainty, we do not even need a very robust statistical analysis. Just rememb…

JSP入门

一、什么是JSP&#xff1f; JSP&#xff08;Java Server Pages)是由Sun Microsystems公司倡导、许多公司参与一起建立的一种动态网页技术标准。JSP技术有点类似ASP技术&#xff0c;它是在传统的网页HTML文件(*.htm,*.html)中插入Java程序段(Scriptlet)和JSP标记(tag)&#xff0…

初学c++

看了两章不到。。随意记录下。 #include<iostream> #include<string> using std::cout; using std::endl; double calculation(double a,double b,char op) {switch(op){case : return ab;case -:return a-b;case *:return a*b;case /:return a/b;}}double num0;do…

从头开始vue创建项目_我正在以设计师的身份开始一个被动的收入项目。 从头开始。...

从头开始vue创建项目Do you ever read an article on Medium (or elsewhere) about passive income, side projects and big money making blogs? When I read such an article it looks like it is easy to do yourself if you just put in the work. To see if that is the …

Exaple2_1(显示转换)

public class Example2_1{ public static void main(String arg[]){ char ca; System.out.println(""c"unicode:"(int)c); System.out.println(":"); for(int i(int)c;i<c25;i){ System.out.println(""(char)i); } }}转载于…

英国文化影响管理风格_文化如何影响用户体验

英国文化影响管理风格重点 (Top highlight)The Internet makes the world a smaller place. You can make money or gain users outside of your demographic with a digital product or service easier than a physical business. But, is selling the exact same design of t…

ubuntu12.04安装教程

第一部分&#xff1a;准备Ubuntu12.04的启动盘 Ubuntu支持可移动盘和CDROM安装&#xff0c;笔者选择后者。在Ubuntu官网http://www.ubuntu.org.cn/download/desktop下载Ubuntu镜像文件(.iso)&#xff0c;通过光盘刻录机将该镜像文件刻录到一张空白CD/DVD上。 第二部分&#xff…

element ui 空格_空格是您的UI朋友。 大量使用它。

element ui 空格Originally published at marcandrew.me on July 30th, 2020.最初于 2020 年7月30日 在 marcandrew.me 上 发布 。 Ah good old White Space. One of the simplest things to add to your designs to improve both your UIs, and user experience. Let me shar…

solaris 11 vim的安装【转】

转自&#xff1a;http://www.itkee.com/os/detail-4a4.html 下面是安装方法&#xff0c;拿出来分享一下 ①下载软件的地方&#xff1a; ftp://ftp.sunfreeware.com/pub/freeware/intel/10/ http://artfiles.org/sunfreeware.com/pub/freeware/i386/10/ vim-7.2-sol10-x86-local…

看看老外是如何理解抽象类的

下面是我翻译的关于帮助理解抽象类的例子。 这是一个例子帮助我们理解抽象类。在我看来这是一个非常简单的方法。让我们一起来看看下面的代码&#xff1a; <?php class Fruit { private $color; public function eat() { //chew } publi…

qt 设计师缩放_重新设计缩放体验

qt 设计师缩放With the COVID-19 pandemic hitting countries across the world, a lot of people have now switched to video meetings. Be it for your official meetings, webinars, entertainment sessions — video meetings are the new normal. We saw these video mee…