浅谈android中的异步加载一

来源:互联网 发布:vincent知乎 编辑:程序博客网 时间:2024/05/18 22:47
1、为什么需要异步加载。

    因为我们都知道在Android中的是单线程模型,不允许其他的子线程来更新UI,只允许UI线程(主线程更新UI),否则会多个线程都去更新UI会造成UI的一个混乱有些耗时的操纵(例如网络请求等),如果直接放到主线程中去请求的话则会造成主线程阻塞,而我们系统有规定的响应时间,当响应的时间超过了了阻塞的时间就会造成"Application No Response",也就是我们熟知的ANR错误解决上述问题的时候:我们一般使用的是线程或者线程池+Handler机制如果线程拿到一个数据需要去更新UI,那么就需要Handler把子线程的更新UI的数据发消息给主线程,从而让主线程去更新UI那么还在使用Thread或ThreadPool+Handler的你是否已经厌倦这些繁琐的操纵而且你会发现这些操作的代码都很类似。所以AsyncTask就应运而生了。

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. 那么我们先从源码中的介绍来认识一下AsyncTask.大家别看源码介绍都这么多,实际上看源码更注重是一个整体意思的理解,而不是深入细节,否则深入进去将不可自拔,那么我也是大概从整体的意思来介绍一下源码中所介绍的AsyncTask  
  2. 大致意思如下:  
  3. /** 
  4.  * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to 
  5.  * perform background operations and publish results on the UI thread without 
  6.  * having to manipulate threads and/or handlers.</p> 
  7.  
  8.  上面的大致意思:AsyncTask异步加载可以很合适很容易在UI线程(主线程)使用,这个类允许做一些后台耗时的操作并且发送结果 
  9. 给主线程而不需要借助多线程和Handler 
  10.  
  11.  * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} 
  12.  * and does not constitute a generic threading framework. AsyncTasks should ideally be 
  13.  * used for short operations (a few seconds at the most.) If you need to keep threads 
  14.  * running for long periods of time, it is highly recommended you use the various APIs 
  15.  * provided by the <code>java.util.concurrent</code> pacakge such as {@link Executor}, 
  16.  * {@link ThreadPoolExecutor} and {@link FutureTask}.</p> 
  17.  
  18.  *上面的大致意思:AsyncTask被设计成一个围绕着Thread和Handler的帮助类并且不需要建立一个泛型Thread线程框架 
  19. 注意:实际上AsyncTask建议被使用在稍微短时间的耗时操作(最多是十几秒或者几十秒),如果你的操作 
  20. 需要更长的时间,那么就不建议使用AsyncTask,并且强烈建议你使用java.util.concurrent包中提供的Executor,ThreadPoolExecutor,FutureTask 
  21.  
  22.  * <p>An asynchronous task is defined by a computation that runs on a background thread and 
  23.  * whose result is published on the UI thread. An asynchronous task is defined by 3 generic 
  24.  * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, 
  25.  * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>, 
  26.  * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p> 
  27.  
  28.  *上面的大致意思:一个异步加载是通过运行在后台的线程并且把结果发送给UI线程定义的,一个异步加载通过三个参数泛型,Params,Progress,Result和四个回调方法onPreExecute,doInBackground,onProgressUpdate,onPostExecute来定义的 
  29.  * 
  30.  <div class="special reference"> 
  31.  * <h3>Developer Guides</h3> 
  32.  * <p>For more information about using tasks and threads, read the 
  33.  * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and 
  34.  * Threads</a> developer guide.</p> 
  35.  * </div> 
  36.  * 
  37.  * <h2>Usage</h2> 
  38.  * <p>AsyncTask must be subclassed to be used. The subclass will override at least 
  39.  * one method ({@link #doInBackground}), and most often will override a 
  40.  * second one ({@link #onPostExecute}.)</p> 
  41.  * 
  42.  上面的大致意思::它的用法:异步任务必须被子类继承才能被使用,这个子类至少要去实现一个回调方法#doInBackground,并且通常一般还会重写第二个#onPostExecute方法 
  43.  * <p>Here is an example of subclassing:</p> 
  44.  * <pre class="prettyprint"> 
  45.  * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
  46.  *     protected Long doInBackground(URL... urls) { 
  47.  *         int count = urls.length; 
  48.  *         long totalSize = 0; 
  49.  *         for (int i = 0; i < count; i++) { 
  50.  *             totalSize += Downloader.downloadFile(urls[i]); 
  51.  *             publishProgress((int) ((i / (float) count) * 100)); 
  52.  *             // Escape early if cancel() is called 
  53.  *             if (isCancelled()) break; 
  54.  *         } 
  55.  *         return totalSize; 
  56.  *     } 
  57.  * 
  58.  *     protected void onProgressUpdate(Integer... progress) { 
  59.  *         setProgressPercent(progress[0]); 
  60.  *     } 
  61.  * 
  62.  *     protected void onPostExecute(Long result) { 
  63.  *         showDialog("Downloaded " + result + " bytes"); 
  64.  *     } 
  65.  * } 
  66.  * </pre> 
  67.  * 
  68.  * <p>Once created, a task is executed very simply:</p> 
  69.  * <pre class="prettyprint"> 
  70.  * new DownloadFilesTask().execute(url1, url2, url3); 
  71.  * </pre> 
  72.  * 
  73.  * <h2>AsyncTask's generic types</h2> 
  74.  * <p>The three types used by an asynchronous task are the following:</p> 
  75.  * <ol> 
  76.  *     <li><code>Params</code>, the type of the parameters sent to the task upon 
  77.  *     execution.</li> 
  78.  *     <li><code>Progress</code>, the type of the progress units published during 
  79.  *     the background computation.</li> 
  80.  *     <li><code>Result</code>, the type of the result of the background 
  81.  *     computation.</li> 
  82.  * </ol> 
  83.  * <p>Not all types are always used by an asynchronous task. To mark a type as unused, 
  84.  * simply use the type {@link Void}:</p> 
  85.  * <pre> 
  86.  * private class MyTask extends AsyncTask<Void, Void, Void> { ... } 
  87.  * </pre> 
  88.  *上面意思:介绍了异步加载的泛型,这里会在本文中有介绍 
  89.  * <h2>The 4 steps</h2> 
  90.  * <p>When an asynchronous task is executed, the task goes through 4 steps:</p> 
  91.  * <ol> 
  92.  *     <li>{@link #onPreExecute()}, invoked on the UI thread before the task 
  93.  *     is executed. This step is normally used to setup the task, for instance by 
  94.  *     showing a progress bar in the user interface.</li> 
  95.  *     <li>{@link #doInBackground}, invoked on the background thread 
  96.  *     immediately after {@link #onPreExecute()} finishes executing. This step is used 
  97.  *     to perform background computation that can take a long time. The parameters 
  98.  *     of the asynchronous task are passed to this step. The result of the computation must 
  99.  *     be returned by this step and will be passed back to the last step. This step 
  100.  *     can also use {@link #publishProgress} to publish one or more units 
  101.  *     of progress. These values are published on the UI thread, in the 
  102.  *     {@link #onProgressUpdate} step.</li> 
  103.  *     <li>{@link #onProgressUpdate}, invoked on the UI thread after a 
  104.  *     call to {@link #publishProgress}. The timing of the execution is 
  105.  *     undefined. This method is used to display any form of progress in the user 
  106.  *     interface while the background computation is still executing. For instance, 
  107.  *     it can be used to animate a progress bar or show logs in a text field.</li> 
  108.  *     <li>{@link #onPostExecute}, invoked on the UI thread after the background 
  109.  *     computation finishes. The result of the background computation is passed to 
  110.  *     this step as a parameter.</li> 
  111.  * </ol> 
  112.  * 上面意思:介绍了异步加载的四个回调方法执行的时机,这里会在本文中有详细介绍 
  113.  * <h2>Cancelling a task</h2> 
  114.  * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking 
  115.  * this method will cause subsequent calls to {@link #isCancelled()} to return true. 
  116.  * After invoking this method, {@link #onCancelled(Object)}, instead of 
  117.  * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} 
  118.  * returns. To ensure that a task is cancelled as quickly as possible, you should always 
  119.  * check the return value of {@link #isCancelled()} periodically from 
  120.  * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p> 
  121.  *上面意思:删除一个异步任务,一个任务可以在任何时候被删除,有个cancel方法boolean类型,cancel方法调用将会导致随继调用#isCancelled方法,并返回true 
  122.  
  123.  * <h2>Threading rules</h2> 
  124.  * <p>There are a few threading rules that must be followed for this class to 
  125.  * work properly:</p> 
  126.  * <ul> 
  127.  *     <li>The AsyncTask class must be loaded on the UI thread. This is done 
  128.  *     automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li> 
  129.  *     <li>The task instance must be created on the UI thread.</li> 
  130.  *     <li>{@link #execute} must be invoked on the UI thread.</li> 
  131.  *     <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, 
  132.  *     {@link #doInBackground}, {@link #onProgressUpdate} manually.</li> 
  133.  *     <li>The task can be executed only once (an exception will be thrown if 
  134.  *     a second execution is attempted.)</li> 
  135.  * </ul> 
  136.  *上面的大致意思:线程的规则:1、异步任务类必须在UI线程加载,这个会自动被android.os.Build.VERSION_CODES#JELLY_BEAN完成 
  137.                                           2、异步任务的实例化必须在UI线程中实现,即异步任务的对象必须在UI线程创建 
  138.                       3、#execute方法必须在UI线程中被调用 
  139.                       4、不要自己手动去调用#onPreExecute,#onPostExecute,#doInBackground,#onProgressUpdate方法,这些都是自动调用的 
  140.                       5、异步任务只会仅仅执行一次 
  141.  * <h2>Memory observability</h2> 
  142.  * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following 
  143.  * operations are safe without explicit synchronizations.</p> 
  144.  * <ul> 
  145.  *     <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them 
  146.  *     in {@link #doInBackground}. 
  147.  *     <li>Set member fields in {@link #doInBackground}, and refer to them in 
  148.  *     {@link #onProgressUpdate} and {@link #onPostExecute}. 
  149.  * </ul> 
  150.  *上面的大致意思:异步任务保证了所有的回调方法都是异步加载的,并且操作是安全的没有线程同步的冲突 
  151.  * <h2>Order of execution</h2> 
  152.  * <p>When first introduced, AsyncTasks were executed serially on a single background 
  153.  * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed 
  154.  * to a pool of threads allowing multiple tasks to operate in parallel. Starting with 
  155.  * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single 
  156.  * thread to avoid common application errors caused by parallel execution.</p> 
  157.  * <p>If you truly want parallel execution, you can invoke 
  158.  * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with 
  159.  * {@link #THREAD_POOL_EXECUTOR}.</p> 
  160.  */  
  161. 上面的大致意思:当第一次介绍,异步任务被有序地执行在一个后台的单一线程上,开始通过android.os.Build.VERSION_CODES#DONUT  
  162. 它将被一个线程池允许多任务被执行在一个平行线上而改变。  

2、AsyncTask为何而生
     子线程中更新UI
     封装、简化了异步操作
3、AsyncTask的基本结构
AsyncTask是一个抽象类通常用于被继承,继承Async还必须指定三个泛型参数
params:启动后台任务时输入的参数类型
progress:后台任务执行中返回的进度值的类型
result:后台执行任务完成后返回的结果类型


AsyncTask子类的四个回调方法:
onPreExecute()方法:选择性重写,在执行后台任务前被调用。(注意:选择性重写,在主线程调用,一般用于完成一些初始化的操作)
doInBackground方法:必须重写,在异步执行后台线程将要完成的任务时被调用。(注:必须重写,在子线程调用,用于执行耗时的操作)
onPostExecute方法:选择性重写(虽说是选择性重写,但是一般都会去重写,因为可以仔细想想,我一般开启的异步任务,都需要得到
异步任务后返回的数据,所以这时候你就得重写该方法),在doInBackground方法完后,去调用。并且该方法还有一个参数result就是
doInBackground方法的返回值也就是执行完异步任务后得到的返回值。(注意:一般都会去重写,在主线程调用,一般用于返回执行完异步任务返回的结果)
onProgressUpdate方法:选择性重写,除非你在doInBackground方法中手动调用publishProgress方法时候更新任务进度后,才会去重写和被回调.
(选择性重写(一般当在doInBackground方法中手动调用publishProgress才会去重写),在主线程中调用,一般用于得到子线程执行任务的进度值,并且把该进度值更新到UI线程)


4、AsyncTask中的三个泛型参数的类型与四个方法中参数的关系。
第一个参数类型为Params的泛型:
                                                ----决定了----->AsyncTask子类的实例调用execute()方法中传入参数类型,参数为该类型的可变长数组
                                                ----决定了----->doInBackground()方法的参数类型,参数为该类型的可变长数组
第二个参数类型为Progress的泛型:
                                               ----决定了------>在doInBackground方法中手动调用publishProgress方法中传入参数的类型,  参数为该类型的可变长数组
      ----决定了----->onProgressUpdate()方法中的参数类型,参数为该类型的可变长数组
第三个参数类型为Result的泛型:
                                               ----决定了------>doInBackground()方法的返回值的类型
      ----决定了------>onPostExecute方法的参数的类型


5、AsyncTask中的各个方法参数之间的传递关系:
通过总结了上面的类型参数关系实际上他们之间的参数传递关系也就出来了下面将通过一张参数传递图来说明他们之间的关系



6、从源码的角度将Thread+Handler机制与AsyncTask类比。
我们应该更熟悉Thread+Handler机制的这种模式来实现异步任务的,对于你还在使用该模式的并想要使用AsyncTask的,
我想将Thread+Handler机制与AsyncTask的类比的方法来学习AsyncTask应该对你更有用。实际上AsyncTask就是对
Thread+Handler的封装,只是一些操作被封装了而已。所以既然是一样的,你肯定就能在AsyncTask中找到Thread+Handler的影子。
类比一:我们首先来从外部的结构来说,外面很简单就是通过AsyncTask子类的一个实例调用execute()方法------->类似于我们在开启子线程的start()方法
类比二:再进入内部看它的四个重写方法,在四个方法中只有一个doInBackground是在子线程中执行的,它将实现耗时操作的代码---这就类似于子线程中
的run方法。
类比三:再来看在doInBackground方法中手动调用的publishProgress方法,它在子线程被调用,并传入子线程执行异步任务的进度-----这就类似于在子线程
中的Handler中的sendMessage方法向主线程发消息的方式,把子线程中的数据发给主线程。
类比四:通过类比三,我们很容易想到接下要做的类比,onProgressUpdate()方法处于主线程,它的参数就是publishProgress传来的,---这就类似于在主线程中的Handler中的handlerMessage
方法用于接收来自子线程中的数据。如果你觉得有所疑问的话,那么我们一起来来看看源码是怎么说的。
publishProgress的源码:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * This method can be invoked from {@link #doInBackground} to 
  3.  * publish updates on the UI thread while the background computation is 
  4.  * still running. Each call to this method will trigger the execution of 
  5.  * {@link #onProgressUpdate} on the UI thread. 
  6.  * 
  7.  * {@link #onProgressUpdate} will note be called if the task has been 
  8.  * canceled. 
  9.  * 
  10.  * @param values The progress values to update the UI with. 
  11.  * 
  12.  * @see #onProgressUpdate 
  13.  * @see #doInBackground 
  14.  */  
  15. protected final void publishProgress(Progress... values) {  
  16.     if (!isCancelled()) {  
  17.         sHandler.obtainMessage(MESSAGE_POST_PROGRESS,  
  18.                 new AsyncTaskResult<Progress>(this, values)).sendToTarget();  
  19.     }  
  20. }  


    在publishProgress方法中有一个 sHandler的InternalHandler对象,而InternalHandler也就是继承于Handler,通过sHandler的obtainMessage
    方法把我们的传入的values封装成Message,然后通过滴啊用sendToTarget()方法发送我们封装好的Message
    如果还有疑问的话,我们继续来看obtainMessage方法和sendToTarget()的源码你就会明白了。
[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1.   /** 
  2.  *  
  3.  * Same as {@link #obtainMessage()}, except that it also sets the what and obj members  
  4.  * of the returned Message. 
  5.  *  
  6.  * @param what Value to assign to the returned Message.what field. 
  7.  * @param obj Value to assign to the returned Message.obj field. 
  8.  * @return A Message from the global message pool. 
  9.  */  
  10. public final Message obtainMessage(int what, Object obj)  
  11. {  
  12.     return Message.obtain(this, what, obj);  
  13. }  


可以看到实际上就是在封装我们消息,有消息标识what参数,和obj参数也就是我们传入的value,最后通过我们非常熟悉的Message.obtain方法
得到Message对象,看到这里是不是和清楚了,实际上本质还是和原来的Thread-Handler模式一样
消息封装好了,就通过sendToTarget方法发送消息,我们再次来看下sendToTarget的源码,看它是不是做了发送消息的事
[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Sends this Message to the Handler specified by {@link #getTarget}. 
  3.  * Throws a null pointer exception if this field has not been set. 
  4.  */  
  5. public void sendToTarget() {  
  6.     target.sendMessage(this);  
  7. }  


target.sendMessage(this);果然它如我们所料,它的确做了发送消息的事。我相信大家看到这应该明白了异步加载真正原理,实际上它并没有我们想象的那么高大上,只不过是在原来的Thread+Handler的基础上
进行了高度封装而已。

7、AsyncTask中的四个方法执行顺序是怎么样的呢,下面我们将通过一个demo中的Log打印输出来说明。

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.mikyou.utils;  
  2.   
  3.   
  4. import android.os.AsyncTask;  
  5. import android.util.Log;  
  6.   
  7.   
  8. public class MikyouAsyncTask extends AsyncTask<Void, Void, Void>{  
  9. <span style="white-space:pre">    </span>@Override  
  10. <span style="white-space:pre">    </span>protected void onPreExecute() {  
  11. <span style="white-space:pre">        </span>Log.d("mikyou""执行后台任务前调用onPreExecute");  
  12. <span style="white-space:pre">        </span>super.onPreExecute();  
  13. <span style="white-space:pre">    </span>}  
  14. <span style="white-space:pre">    </span>@Override  
  15. <span style="white-space:pre">    </span>protected Void doInBackground(Void... params) {  
  16. <span style="white-space:pre">        </span>publishProgress();  
  17. <span style="white-space:pre">        </span>Log.d("mikyou""正在执行后台任务调用doInBackground");  
  18. <span style="white-space:pre">        </span>return null;  
  19. <span style="white-space:pre">    </span>}  
  20. <span style="white-space:pre">    </span>@Override  
  21. <span style="white-space:pre">    </span>protected void onProgressUpdate(Void... values) {  
  22. <span style="white-space:pre">        </span>Log.d("mikyou""在doInBackground调用publishProgress后才会调用onProgressUpdate");  
  23. <span style="white-space:pre">        </span>super.onProgressUpdate(values);  
  24. <span style="white-space:pre">    </span>}  
  25. <span style="white-space:pre">    </span>@Override  
  26. <span style="white-space:pre">    </span>protected void onPostExecute(Void result) {  
  27. <span style="white-space:pre">        </span>Log.d("mikyou""后台任务执行完后调用onPostExecute");  
  28. <span style="white-space:pre">        </span>super.onPostExecute(result);  
  29. <span style="white-space:pre">    </span>}  
  30.   
  31.   
  32. }  
运行结果:

通过以上的demo我们大致了解AsyncTask几个方法执行情况。

下面我们将通过一个异步加载网络图片的知识体会一下其中的工作原理。


MikyouAsyncTaskImageUtils异步加载的子类:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.mikyou.utils;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.InputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.MalformedURLException;  
  7. import java.net.URL;  
  8.   
  9. import android.graphics.Bitmap;  
  10. import android.graphics.BitmapFactory;  
  11. import android.os.AsyncTask;  
  12. //因为是网络加载一张图片,所以传入参数为URL为String类型,并且返回一个Bitmap对象  
  13. public class MikyouAsyncTaskImageUtils extends AsyncTask<String, Void, Bitmap>{  
  14.     private Bitmap mBitmap;  
  15.     private OnAsyncTaskImageListener listener;  
  16.     @Override  
  17.     protected void onPreExecute() {//在执行异步任务之前调用,做一些初始化的操作  
  18.         super.onPreExecute();  
  19.     }  
  20.     @Override  
  21.     protected Bitmap doInBackground(String... params) {  
  22.         //写耗时的网络请求操作  
  23.         String url=params[0];//因为只传了一个URL参数  
  24.   
  25.         try {  
  26.             URL mURL=new URL(url);  
  27.             HttpURLConnection conn=(HttpURLConnection) mURL.openConnection();  
  28.             Thread.sleep(3000);//为了看到ProgressBar加载的效果,不会因为很快就加载完了,让它sleep 3秒  
  29.             InputStream is=conn.getInputStream();  
  30.             BufferedInputStream bis=new BufferedInputStream(is);  
  31.             mBitmap=BitmapFactory.decodeStream(bis);  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.         return mBitmap;  
  36.     }  
  37.     @Override  
  38.     protected void onPostExecute(Bitmap result) {  
  39.         //拿到Bitmap的返回值,就需要将它传递给MainActivity中的iv让它设置这个mBitmap对象  
  40.         /** 
  41.          * 这里有三种方法实现:第一直接把该类作为内部类放入Activity中就不需要传递mBitmap 
  42.          * 因为iv在MainActivity中是全局的直接设置就可以了,实现数据共享 
  43.          *  
  44.          *                                         第二将该类放到另外一个包内,此时就需要将外面的ImageView对象,通过构造器传入 
  45.          *                                         然后再该类中去直接给ImageView对象设置Bitmap即可 
  46.          *                                          
  47.          *                                         第三则是我这里要使用的,这个类也是在另外一个包内,采用的是把这个Bitmap对象 
  48.          *                                         通过自定义一个监听器,通过监听器的回调方法将我们该方法中的result的Bitmap对象 
  49.          *                                         传出去,让外面直接在回调方法中设置BItmap 
  50.          * 有的人就要疑问,为何我不能直接通过该类公布出去一个mBItmap对象的getter方法,让那个外面 
  51.          * 直接通过getter方法拿到mBitmap,有这种想法,可能你忽略了一个很基本的问题就是,我们 
  52.          * 这个网路请求的任务是异步的,也就是这个BItmap不知道什么时候有值,当主线程去调用 
  53.          * getter方法时候,子线程的网络请求还来不及拿到Bitmap,那么此时主线程拿到的只能为空 
  54.          * 那就会报空指针的错误了,所以我们自己定义一个监听器,写一个回调方法,当网络请求拿到了 
  55.          * Bitmap才会回调即可。 
  56.          * 自定一个监听器: 
  57.          *  1、首先得去写一个接口 
  58.          *  2 然后在类中保存一个接口类型的引用  
  59.          *  3 然后写一个setOnAsyncTaskImageListener 
  60.          * 方法初始化那个接口类型的引用   
  61.          * 4、最后在我们的onPostExecute方法中调用接口中的抽象方法, 
  62.          * 并且把我们得到的result作为参数传入即可 
  63.          *                     
  64.          * */  
  65.     <span style="white-space:pre">    </span>if (listener!=null) {  
  66. <span style="white-space:pre">            </span>listener.asyncTaskImageListener(result);  
  67. <span style="white-space:pre">            </span>  
  68. <span style="white-space:pre">        </span>}  
  69.         super.onPostExecute(result);  
  70.     }  
  71.     //  
  72.     public void setOnAsyncTaskImageListener(OnAsyncTaskImageListener listener){  
  73.         this.listener=listener;  
  74.     }  
  75. }  
[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. OnAsyncTaskImageListener接口  
[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.mikyou.utils;  
  2.   
  3.   
  4. import android.graphics.Bitmap;  
  5.   
  6.   
  7. public interface OnAsyncTaskImageListener {  
  8. <span style="white-space:pre">    </span>public void asyncTaskImageListener(Bitmap bitmap);  
  9. }  

MainActivity:

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.mikyou.asynctask;  
  2.   
  3. import com.mikyou.utils.MikyouAsyncTaskImageUtils;  
  4. import com.mikyou.utils.OnAsyncTaskImageListener;  
  5.   
  6. import android.app.Activity;  
  7. import android.graphics.Bitmap;  
  8. import android.os.Bundle;  
  9. import android.view.Menu;  
  10. import android.view.MenuItem;  
  11. import android.view.View;  
  12. import android.widget.ImageView;  
  13. import android.widget.ProgressBar;  
  14.   
  15. public class MainActivity extends Activity implements OnAsyncTaskImageListener{  
  16.     private ImageView iv;  
  17.     private ProgressBar bar;  
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.         initView();  
  23.         MikyouAsyncTaskImageUtils mikyouAsyncTaskImageUtils=new MikyouAsyncTaskImageUtils();  
  24.         mikyouAsyncTaskImageUtils.execute("http://b.hiphotos.baidu.com/image/h%3D360/sign=8918c5efbe3eb1355bc7b1bd961ea8cb/7a899e510fb30f244bb50504ca95d143ad4b038d.jpg");  
  25.         mikyouAsyncTaskImageUtils.setOnAsyncTaskImageListener(this);//注册我们自己定义的监听器  
  26.     }  
  27.     private void initView() {  
  28.         iv=(ImageView) findViewById(R.id.iv);  
  29.         bar=(ProgressBar) findViewById(R.id.bar);  
  30.     }  
  31.     @Override  
  32.     public void asyncTaskImageListener(Bitmap bitmap) {//实现监听器的接口后,重写回调方法,这里的Bitmap对象就是我们从AsyncTask中的onPostExecute方法中传来的result  
  33.         bar.setVisibility(View.INVISIBLE);  
  34.         iv.setImageBitmap(bitmap);  
  35.     }  
  36.   
  37. }  

运行结果:


下面我们还通过一个demo使用一下onProgressUpdate方法,publishProgress方法,这个demo就用一个模拟下载进度条更新。

MikyouAsyncTaskProgressBarUtils

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.mikyou.utils;  
  2.   
  3. import android.os.AsyncTask;  
  4. import android.widget.ProgressBar;  
  5. import android.widget.TextView;  
  6.   
  7. public class MikyouAsyncTaskProgressBarUtils extends AsyncTask<Void, Integer, String>{  
  8.     private TextView tv;  
  9.     private ProgressBar bar;  
  10.     public MikyouAsyncTaskProgressBarUtils(TextView tv,ProgressBar bar){//这里我就采用构造器将TextView,ProgressBar直接传入,然后在该类中直接更新UI  
  11.         this.bar=bar;  
  12.         this.tv=tv;  
  13.   
  14.     }  
  15.     @Override  
  16.     protected String doInBackground(Void... params) {  
  17.         for(int i=1;i<101;i++){  
  18.             try {  
  19.                 Thread.sleep(1000);  
  20.             } catch (InterruptedException e) {  
  21.                 e.printStackTrace();  
  22.             }  
  23.             publishProgress(i);  
  24.         }  
  25.         return "下载完成";  
  26.     }  
  27.     @Override  
  28.     protected void onProgressUpdate(Integer... values) {  
  29.         bar.setProgress(values[0]);  
  30.         tv.setText("下载进度:"+values[0]+"%");  
  31.         super.onProgressUpdate(values);  
  32.     }  
  33.     @Override  
  34.     protected void onPostExecute(String result) {  
  35.         tv.setText(result);  
  36.         super.onPostExecute(result);  
  37.     }  
  38. }  

MainActivity

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.mikyou.asynctask;  
  2.   
  3. import com.mikyou.utils.MikyouAsyncTaskProgressBarUtils;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.ProgressBar;  
  10. import android.widget.TextView;  
  11.   
  12. public class MainActivity extends Activity {  
  13.     private Button downLoad;  
  14.     private ProgressBar bar;  
  15.     private TextView tv;  
  16.     @Override  
  17.     protected void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.activity_main);  
  20.         initView();  
  21.     }  
  22.     private void initView() {  
  23.         bar=(ProgressBar) findViewById(R.id.bar);  
  24.         tv=(TextView) findViewById(R.id.tv);  
  25.     }  
  26.     public void download(View view){  
  27.         MikyouAsyncTaskProgressBarUtils mikyouAsyncTaskProgressBarUtils=new MikyouAsyncTaskProgressBarUtils(tv, bar);  
  28.         mikyouAsyncTaskProgressBarUtils.execute();  
  29.     }  
  30.   
  31. }  
布局:

[html] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button  
  8.         android:id="@+id/start_download"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:onClick="download"  
  12.         android:text="开始下载" />  
  13.   
  14.     <ProgressBar  
  15.         android:id="@+id/bar"  
  16.         style="@android:style/Widget.ProgressBar.Horizontal"  
  17.         android:layout_width="match_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:layout_marginTop="20dp" />  
  20.   
  21.     <TextView  
  22.         android:id="@+id/tv"  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="wrap_content"  
  25.            android:layout_marginTop="20dp"   
  26.         android:text="下载进度:" />  
  27.   
  28. </LinearLayout>  


运行结果:


那么,关于异步加载的入门也就到这儿,随后将深入理解异步加载

0 0
原创粉丝点击