android基础知识02——线程安全5: AsyncTask

 android的UI操作不是线程安全的,同时也只有主线程才能够操作UI,同时主线程对于UI操作有一定的时间限制(最长5秒)。为了能够做一些比较耗时的操作(比如下载、打开大文件等),android提供了一些列机制。《android基础知识02——线程安全》系列文章就是参考了网上许多网友的文章后,整理出来的一个系列,介绍了主要的方法。分别如下:

         android基础知识02——线程安全1:定义及例子

        android基础知识02——线程安全2:handler、message、runnable

        android基础知识02——线程安全3:Message,MessageQueue,Handler,Looper

        android基础知识02——线程安全4:HandlerThread

        android基础知识02——线程安全5: AsyncTask

        

在前面介绍的线程安全中,为了操作主线程的UI,使用子线程进行处理。在android开发中,还可以使用另外两种方法进行处理:

        HandlerThread
        AsyncTask

        本文介绍AsyncTask。

       在开发Android应用时必须遵守单线程模型的原则: Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行。在单线程模型中始终要记住两条法则: 
1. 不要阻塞UI线程 
2. 确保只在UI线程中访问Android UI工具包 
      当一个程序第一次启动时,Android会同时启动一个对应的主线程(Main Thread),主线程主要负责处理与UI相关的事件,如:用户的按键事件,用户接触屏幕的事件以及屏幕绘图事件,并把相关的事件分发到对应的组件进行处理。所以主线程通常又被叫做UI线程。 
      比如说从网上获取一个网页,在一个TextView中将其源代码显示出来,这种涉及到网络操作的程序一般都是需要开一个线程完成网络访问,但是在获得页面源码后,是不能直接在网络操作线程中调用TextView.setText()的.因为其他线程中是不能直接访问主UI线程成员 。
android提供了几种在其他线程中访问UI线程的方法。 
Activity.runOnUiThread( Runnable ) 
View.post( Runnable ) 
View.postDelayed( Runnable, long ) 
Hanlder 
这些类或方法同样会使你的代码很复杂很难理解。然而当你需要实现一些很复杂的操作并需要频繁地更新UI时这会变得更糟糕。 
     为了解决这个问题,Android 1.5提供了一个工具类:AsyncTask,它使创建需要与用户界面交互的长时间运行的任务变得更简单。相对来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和Handler即可实现。 
AsyncTask是抽象类.AsyncTask定义了三种泛型类型 Params,Progress和Result。 
  Params 启动任务执行的输入参数,比如HTTP请求的URL。 
  Progress 后台任务执行的百分比。 
  Result 后台执行任务最终返回的结果,比如String。 
     AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,这些方法不应该由应用程序调用,开发者需要做的就是实现这些方法。 
  1) 子类化AsyncTask 
  2) 实现AsyncTask中定义的下面一个或几个方法 
     onPreExecute(), 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。 
    doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。 
    onProgressUpdate(Progress...),在publishProgress方法被调用后,UI thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。 
    onPostExecute(Result), 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread. 
为了正确的使用AsyncTask类,以下是几条必须遵守的准则: 
  1) Task的实例必须在UI thread中创建 
  2) execute方法必须在UI thread中调用 
  3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法 
  4) 该task只能被执行一次,否则多次调用时将会出现异常 
      doInBackground方法和onPostExecute的参数必须对应,这两个参数在AsyncTask声明的泛型参数列表中指定,第一个为doInBackground接受的参数,第二个为显示进度的参数,第第三个为doInBackground返回和onPostExecute传入的参数。

        需要说明AsyncTask不能完全取代线程,在一些逻辑较为复杂或者需要在后台反复执行的逻辑就可能需要线程来实现了。
       从网上获取一个网页,在一个TextView中将其源代码显示出来

[java]  view plain copy
  1. package test.list;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.InputStream;  
  4. import java.util.ArrayList;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.client.HttpClient;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.impl.client.DefaultHttpClient;  
  11.   
  12. import android.app.Activity;  
  13. import android.app.ProgressDialog;  
  14. import android.content.Context;  
  15. import android.content.DialogInterface;  
  16. import android.os.AsyncTask;  
  17. import android.os.Bundle;  
  18. import android.os.Handler;  
  19. import android.os.Message;  
  20. import android.view.View;  
  21. import android.widget.Button;  
  22. import android.widget.EditText;  
  23. import android.widget.TextView;  
  24.   
  25. public class NetworkActivity extends Activity{  
  26.     private TextView message;  
  27.     private Button open;  
  28.     private EditText url;  
  29.   
  30.     @Override  
  31.     public void onCreate(Bundle savedInstanceState) {  
  32.        super.onCreate(savedInstanceState);  
  33.        setContentView(R.layout.network);  
  34.        message= (TextView) findViewById(R.id.message);  
  35.        url= (EditText) findViewById(R.id.url);  
  36.        open= (Button) findViewById(R.id.open);  
  37.        open.setOnClickListener(new View.OnClickListener() {  
  38.            public void onClick(View arg0) {  
  39.               connect();  
  40.            }  
  41.        });  
  42.   
  43.     }  
  44.   
  45.     private void connect() {  
  46.         PageTask task = new PageTask(this);  
  47.         task.execute(url.getText().toString());  
  48.     }  
  49.   
  50.     class PageTask extends AsyncTask<String, Integer, String> {  
  51.         // 可变长的输入参数,与AsyncTask.exucute()对应  
  52.         ProgressDialog pdialog;  
  53.         public PageTask(Context context){  
  54.             pdialog = new ProgressDialog(context, 0);     
  55.             pdialog.setButton("cancel"new DialogInterface.OnClickListener() {  
  56.              public void onClick(DialogInterface dialog, int i) {  
  57.               dialog.cancel();  
  58.              }  
  59.             });  
  60.             pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {  
  61.              public void onCancel(DialogInterface dialog) {  
  62.               finish();  
  63.              }  
  64.             });  
  65.             pdialog.setCancelable(true);  
  66.             pdialog.setMax(100);  
  67.             pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  68.             pdialog.show();  
  69.   
  70.         }  
  71.         @Override  
  72.         protected String doInBackground(String... params) {  
  73.   
  74.             try{  
  75.   
  76.                HttpClient client = new DefaultHttpClient();  
  77.                // params[0]代表连接的url  
  78.                HttpGet get = new HttpGet(params[0]);  
  79.                HttpResponse response = client.execute(get);  
  80.                HttpEntity entity = response.getEntity();  
  81.                long length = entity.getContentLength();  
  82.                InputStream is = entity.getContent();  
  83.                String s = null;  
  84.                if(is != null) {  
  85.                    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  86.   
  87.                    byte[] buf = new byte[128];  
  88.   
  89.                    int ch = -1;  
  90.   
  91.                    int count = 0;  
  92.   
  93.                    while((ch = is.read(buf)) != -1) {  
  94.   
  95.                       baos.write(buf, 0, ch);  
  96.   
  97.                       count += ch;  
  98.   
  99.                       if(length > 0) {  
  100.                           // 如果知道响应的长度,调用publishProgress()更新进度  
  101.                           publishProgress((int) ((count / (float) length) * 100));  
  102.                       }  
  103.   
  104.                       // 让线程休眠100ms  
  105.                       Thread.sleep(100);  
  106.                    }  
  107.                    s = new String(baos.toByteArray());              }  
  108.                // 返回结果  
  109.                return s;  
  110.             } catch(Exception e) {  
  111.                e.printStackTrace();  
  112.   
  113.             }  
  114.   
  115.             return null;  
  116.   
  117.         }  
  118.   
  119.         @Override  
  120.         protected void onCancelled() {  
  121.             super.onCancelled();  
  122.         }  
  123.   
  124.         @Override  
  125.         protected void onPostExecute(String result) {  
  126.             // 返回HTML页面的内容  
  127.             message.setText(result);  
  128.             pdialog.dismiss();   
  129.         }  
  130.   
  131.         @Override  
  132.         protected void onPreExecute() {  
  133.             // 任务启动,可以在这里显示一个对话框,这里简单处理  
  134.             message.setText(R.string.task_started);  
  135.         }  
  136.   
  137.         @Override  
  138.         protected void onProgressUpdate(Integer... values) {  
  139.             // 更新进度  
  140.               System.out.println(""+values[0]);  
  141.               message.setText(""+values[0]);  
  142.               pdialog.setProgress(values[0]);  
  143.         }  
  144.   
  145.      }  
  146.   
  147. }  

        看了AsyncTask的源码以后,你会在文件头看到如下的申明。在 这个申明中你可以很轻易的了解AsyncTask的使用方法:

[java]  view plain copy
  1. /** 
  2.  * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to 
  3.  * perform background operations and publish results on the UI thread without 
  4.  * having to manipulate threads and/or handlers.</p> 
  5.  * 
  6.  * <p>An asynchronous task is defined by a computation that runs on a background thread and 
  7.  * whose result is published on the UI thread. An asynchronous task is defined by 3 generic 
  8.  * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, 
  9.  * and 4 steps, called <code>begin</code>, <code>doInBackground</code>, 
  10.  * <code>processProgress</code> and <code>end</code>.</p> 
  11.  * 
  12.  * <h2>Usage</h2> 
  13.  * <p>AsyncTask must be subclassed to be used. The subclass will override at least 
  14.  * one method ({@link #doInBackground}), and most often will override a 
  15.  * second one ({@link #onPostExecute}.)</p> 
  16.  * 
  17.  * <p>Here is an example of subclassing:</p> 
  18.  * <pre class="prettyprint"> 
  19.  * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
  20.  *     protected Long doInBackground(URL... urls) { 
  21.  *         int count = urls.length; 
  22.  *         long totalSize = 0; 
  23.  *         for (int i = 0; i < count; i++) { 
  24.  *             totalSize += Downloader.downloadFile(urls[i]); 
  25.  *             publishProgress((int) ((i / (float) count) * 100)); 
  26.  *         } 
  27.  *         return totalSize; 
  28.  *     } 
  29.  * 
  30.  *     protected void onProgressUpdate(Integer... progress) { 
  31.  *         setProgressPercent(progress[0]); 
  32.  *     } 
  33.  * 
  34.  *     protected void onPostExecute(Long result) { 
  35.  *         showDialog("Downloaded " + result + " bytes"); 
  36.  *     } 
  37.  * } 
  38.  * </pre> 
  39.  * 
  40.  * <p>Once created, a task is executed very simply:</p> 
  41.  * <pre class="prettyprint"> 
  42.  * new DownloadFilesTask().execute(url1, url2, url3); 
  43.  * </pre> 
  44.  * 
  45.  * <h2>AsyncTask's generic types</h2> 
  46.  * <p>The three types used by an asynchronous task are the following:</p> 
  47.  * <ol> 
  48.  *     <li><code>Params</code>, the type of the parameters sent to the task upon 
  49.  *     execution.</li> 
  50.  *     <li><code>Progress</code>, the type of the progress units published during 
  51.  *     the background computation.</li> 
  52.  *     <li><code>Result</code>, the type of the result of the background 
  53.  *     computation.</li> 
  54.  * </ol> 
  55.  * <p>Not all types are always used by am asynchronous task. To mark a type as unused, 
  56.  * simply use the type {@link Void}:</p> 
  57.  * <pre> 
  58.  * private class MyTask extends AsyncTask<Void, Void, Void> { ... } 
  59.  * </pre> 
  60.  * 
  61.  * <h2>The 4 steps</h2> 
  62.  * <p>When an asynchronous task is executed, the task goes through 4 steps:</p> 
  63.  * <ol> 
  64.  *     <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task 
  65.  *     is executed. This step is normally used to setup the task, for instance by 
  66.  *     showing a progress bar in the user interface.</li> 
  67.  *     <li>{@link #doInBackground}, invoked on the background thread 
  68.  *     immediately after {@link #onPreExecute()} finishes executing. This step is used 
  69.  *     to perform background computation that can take a long time. The parameters 
  70.  *     of the asynchronous task are passed to this step. The result of the computation must 
  71.  *     be returned by this step and will be passed back to the last step. This step 
  72.  *     can also use {@link #publishProgress} to publish one or more units 
  73.  *     of progress. These values are published on the UI thread, in the 
  74.  *     {@link #onProgressUpdate} step.</li> 
  75.  *     <li>{@link #onProgressUpdate}, invoked on the UI thread after a 
  76.  *     call to {@link #publishProgress}. The timing of the execution is 
  77.  *     undefined. This method is used to display any form of progress in the user 
  78.  *     interface while the background computation is still executing. For instance, 
  79.  *     it can be used to animate a progress bar or show logs in a text field.</li> 
  80.  *     <li>{@link #onPostExecute}, invoked on the UI thread after the background 
  81.  *     computation finishes. The result of the background computation is passed to 
  82.  *     this step as a parameter.</li> 
  83.  * </ol> 
  84.  * 
  85.  * <h2>Threading rules</h2> 
  86.  * <p>There are a few threading rules that must be followed for this class to 
  87.  * work properly:</p> 
  88.  * <ul> 
  89.  *     <li>The task instance must be created on the UI thread.</li> 
  90.  *     <li>{@link #execute} must be invoked on the UI thread.</li> 
  91.  *     <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, 
  92.  *     {@link #doInBackground}, {@link #onProgressUpdate} manually.</li> 
  93.  *     <li>The task can be executed only once (an exception will be thrown if 
  94.  *     a second execution is attempted.)</li> 
  95.  * </ul> 
  96.  */  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值