`
kevin2562
  • 浏览: 116574 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

android AsyncTask

阅读更多
Android中AsyncTask的用法

    * AsyncTask

        看上去修改后的connect()方法已经可用了,但是这种匿名线程的方式是存在缺陷的:
第一,线程的开销较大,如果每个任务都要创建一个线程,那么应用 程序的效率要低很多;
第二,线程无法管理,匿名线程创建并启动后就不受程序的控制了,如果有很多个请求发送,那么就会启动非常多的线程,系统将不堪重负。
另外,前面已经看到,在新线程中更新UI还必须要引入handler,这让代码看上去非常臃肿。

        为了解决这一问题,OPhone在1.5版本引入了AsyncTask。AsyncTask的特点是任务在主线程之外运行,而回调方法是在主线程中执行, 这就有效地避免了使用Handler带来的麻烦。
阅读AsyncTask的源码可知,AsyncTask是使用java.util.concurrent 框架来管理线程以及任务的执行的,concurrent框架是一个非常成熟,高效的框架,经过了严格的测试。这说明AsyncTask的设计很好的解决了 匿名线程存在的问题。

       AsyncTask是抽象类,子类必须实现抽象方法doInBackground(Params... p) ,在此方法中实现任务的执行工作,比如连接网络获取数据等。
通常还应该实现onPostExecute(Result r)方法,因为应用程序关心的结果在此方法中返回。需要注意的是AsyncTask一定要在主线程中创建实例。AsyncTask定义了三种泛型类型 Params,Progress和Result。
    * Params 启动任务执行的输入参数,比如HTTP请求的URL。
    * Progress 后台任务执行的百分比。
    * Result 后台执行任务最终返回的结果,比如String。

       AsyncTask 的执行分为四个步骤,与前面定义的TaskListener类似。每一步都对应一个回调方法,需要注意的是这些方法不应该由应用程序调用,开发者需要做的就是实现这些方法。在任务的执行过程中,这些方法被自动调用。

    * onPreExecute() 当任务执行之前开始调用此方法,可以在这里显示进度对话框。
    * doInBackground(Params...) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。
    * onProgressUpdate(Progress...) 此方法在主线程执行,用于显示任务执行的进度。
    * onPostExecute(Result) 此方法在主线程执行,任务执行的结果作为此方法的参数返回。

       PageTask扩展了AsyncTask,在 doInBackground()方法中读取网页内容。PageTask的源代码如下所示:

   1. // 设置三种类型参数分别为String,Integer,String 
   2.     class PageTask extends AsyncTask<String, Integer, String> { 
   3.  
   4.         // 可变长的输入参数,与AsyncTask.exucute()对应 
   5.         @Override 
   6.         protected String doInBackground(String... params) { 
   7.             try { 
   8.                 HttpClient client = new DefaultHttpClient(); 
   9.                 // params[0] 代表连接的url 
  10.                 HttpGet get = new HttpGet(params[0]); 
  11.                 HttpResponse response = client.execute(get); 
  12.                 HttpEntity entity = response.getEntity(); 
  13.                 long length = entity.getContentLength(); 
  14.                 InputStream is = entity.getContent(); 
  15.                 String s = null; 
  16.                 if (is != null) { 
  17.                     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
  18.                     byte[] buf = new byte[128]; 
  19.                     int ch = -1; 
  20.                     int count = 0; 
  21.                     while ((ch = is.read(buf)) != -1) { 
  22.                         baos.write(buf, 0, ch); 
  23.                         count += ch; 
  24.                         if (length > 0) { 
  25.                             // 如果知道响应的长度,调用publishProgress()更新进度 
  26.                             publishProgress((int) ((count / (float) length) * 100)); 
  27.                         } 
  28.                         // 为了在模拟器中清楚地看到进度,让线程休眠100ms 
  29.                         Thread.sleep(100); 
  30.                     } 
  31.                     s = new String(baos.toByteArray());             } 
  32.                 // 返回结果 
  33.                 return s; 
  34.             } catch (Exception e) { 
  35.                 e.printStackTrace(); 
  36.             } 
  37.             return null; 
  38.         } 
  39.         @Override 
  40.         protected void onCancelled() { 
  41.             super.onCancelled(); 
  42.         } 
  43.         @Override 
  44.         protected void onPostExecute(String result) { 
  45.             // 返回HTML页面的内容 
  46.             message.setText(result); 
  47.         } 
  48.         @Override 
  49.         protected void onPreExecute() { 
  50.             // 任务启动,可以在这里显示一个对话框,这里简单处理 
  51.             message.setText(R.string.task_started); 
  52.         } 
  53.         @Override 
  54.         protected void onProgressUpdate(Integer... values) { 
  55.             // 更新进度 
  56.             message.setText(values[0]); 
  57.         } 
  58.     } 

// 设置三种类型参数分别为String,Integer,String class PageTask extends AsyncTask<String, Integer, String> { // 可变长的输入参数,与AsyncTask.exucute()对应 @Override protected String doInBackground(String... params) { try { HttpClient client = new DefaultHttpClient(); // params[0]代表连接的url HttpGet get = new HttpGet(params[0]); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); String s = null; if (is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[128]; int ch = -1; int count = 0; while ((ch = is.read(buf)) != -1) { baos.write(buf, 0, ch); count += ch; if (length > 0) { // 如果知道响应的长度,调用publishProgress()更新进度 publishProgress((int) ((count / (float) length) * 100)); } // 为了在模拟器中清楚地看到进度,让线程休眠100ms Thread.sleep(100); } s = new String(baos.toByteArray()); } // 返回结果 return s; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(String result) { // 返回HTML页面的内容 message.setText(result); } @Override protected void onPreExecute() { // 任务启动,可以在这里显示一个对话框,这里简单处理 message.setText(R.string.task_started); } @Override protected void onProgressUpdate(Integer... values) { // 更新进度 message.setText(values[0]); } }

      执行PageTask非常简单,只需要调用如下代码。重新运行NetworkActivity,不但可以抓取网页的内容,还可以实时更新读取的进度。读者尝试读取一个较大的网页,看看百分比的更新情况。

   1. PageTask task = new PageTask(); 
   2.         task.execute(url.getText().toString()); 
分享到:
评论
1 楼 无愧衾影 2011-03-27  
怎么上面没有朋友评论哦,

相关推荐

Global site tag (gtag.js) - Google Analytics