Android异步通信机制(三)

AsyncTask

阅读浏览器的代码,可以看到 BrowserActivity.java在Oncreate()里创建了AsyncTask, 为什么不使用前面提到的Handler呢?

AsyncTask的特点是任务在主线程之外运行,而回调方法是在主线程中执行,这就有效地避免了使用Handler带来的麻烦。阅读AsyncTask的源码可知,AsyncTask是使用java.util.concurrent框架来管理线程以及任务的执行的。如果联网请求的的时候使用匿名线程:第一,匿名线程的开销较大,如果每个任务都要创建一个线程,那么应用程序的效率要低很多;第二,匿名线程无法管理,匿名线程创建并启动后就不受程序的控制了,如果有很多个请求发送,那么就会启动非常多的线程,系统将不堪重负。


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

•Params 启动任务执行的输入参数,比如HTTP请求的URL。
•Progress 后台任务执行的百分比。

•Result 后台执行任务最终返回的结果,比如String。


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

•onPreExecute() 当任务执行之前开始调用此方法,可以在这里显示进度对话框。这个方法可以不用实现
•doInBackground(Params...) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publishProgress (Progress...)来更新任务的进度。
•onProgressUpdate(Progress...) 此方法在主线程执行,用于显示任务执行的进度。

•onPostExecute(Result) 此方法在主线程执行,任务执行的结果作为此方法的参数返回。后台的计算结果将通过该方法传递到UI 线程,并且在界面上展示给用户

•onCancelled(),在用户取消线程操作的时候调用。在主线程中调用onCancelled()的时候调用为了正确的使用AsyncTask类,以下是几条必须遵守的准则:

      1) Task的实例必须在UI 线程中创建

      2) execute方法必须在UI 线程中调用

      3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法,需要在UI线程中实例化这个task来调用。

      4) 该task只能被执行一次,否则多次调用时将会出现异常

      doInBackground方法和onPostExecute的参数必须对应,这两个参数在AsyncTask声明的泛型参数列表中指定,第一个为doInBackground接受的参数,第二个为显示进度的参数,第三个为doInBackground返回和onPostExecute传入的参数。

下面通过一个Demo来说明如何使用Android.os.AsyncTask类,通过进度条来显示进行的进度,然后用TextView显示进度值。程序结构图如下:

[1] \layout\main.xml 布局文件源码如下:

[html] view plaincopyprint?

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:layout_width="fill_parent"   

9.          android:layout_height="wrap_content"   

10.         android:text="Hello , Welcome to Andy's Blog!"/>  

11.      <Button  

12.         android:id="@+id/download"  

13.         android:layout_width="fill_parent"  

14.         android:layout_height="wrap_content"  

15.         android:text="Download"/>  

16.      <TextView    

17.         android:id="@+id/tv"  

18.         android:layout_width="fill_parent"   

19.         android:layout_height="wrap_content"   

20.         android:text="当前进度显示"/>  

21.      <ProgressBar  

22.         android:id="@+id/pb"  

23.         android:layout_width="fill_parent"  

24.         android:layout_height="wrap_content"  

25.         style="?android:attr/progressBarStyleHorizontal"/>  

26.  </LinearLayout>  

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="Hello , Welcome to Andy's Blog!"/>
    <Button
       android:id="@+id/download"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="Download"/>
    <TextView  
       android:id="@+id/tv"
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="当前进度显示"/>
    <ProgressBar
       android:id="@+id/pb"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       style="?android:attr/progressBarStyleHorizontal"/>
</LinearLayout>

 

 [2] /src中的MainActivity.java源码如下:

[html] view plaincopyprint?

1.   package com.andyidea.demo;  

2.     

3.   import android.app.Activity;  

4.   import android.os.AsyncTask;  

5.   import android.os.Bundle;  

6.   import android.view.View;  

7.   import android.widget.Button;  

8.   import android.widget.ProgressBar;  

9.   import android.widget.TextView;  

10.    

11.  public class MainActivity extends Activity {  

12.            

13.      Button download;  

14.      ProgressBar pb;  

15.      TextView tv;  

16.        

17.      /** Called when the activity is first created. */  

18.      @Override  

19.      public void onCreate(Bundle savedInstanceState) {  

20.          super.onCreate(savedInstanceState);  

21.          setContentView(R.layout.main);  

22.          pb=(ProgressBar)findViewById(R.id.pb);  

23.          tv=(TextView)findViewById(R.id.tv);  

24.            

25.          download = (Button)findViewById(R.id.download);  

26.          download.setOnClickListener(new View.OnClickListener() {  

27.              @Override  

28.              public void onClick(View v) {  

29.                  DownloadTask dTask = new DownloadTask();  

30.                  dTask.execute(100);  

31.              }  

32.          });  

33.      }  

34.        

35.      class DownloadTask extends AsyncTask<Integer, Integer, String>{  

36.          //后面尖括号内分别是参数(例子里是线程休息时间),进度(publishProgress用到),返回值 类型  

37.            

38.          @Override  

39.          protected void onPreExecute() {  

40.              //第一个执行方法  

41.              super.onPreExecute();  

42.          }  

43.            

44.          @Override  

45.          protected String doInBackground(Integer... params) {  

46.              //第二个执行方法,onPreExecute()执行完后执行  

47.              for(int i=0;i<=100;i++){  

48.                  pb.setProgress(i);  

49.                  publishProgress(i);  

50.                  try {  

51.                      Thread.sleep(params[0]);  

52.                  } catch (InterruptedException e) {  

53.                      e.printStackTrace();  

54.                  }  

55.              }  

56.              return "执行完毕";  

57.          }  

58.    

59.          @Override  

60.          protected void onProgressUpdate(Integer... progress) {  

61.              //这个函数在doInBackground调用publishProgress时触发,虽然调用时只有一个参数  

62.              //但是这里取到的是一个数组,所以要用progesss[0]来取值  

63.              //第n个参数就用progress[n]来取值  

64.              tv.setText(progress[0]+"%");  

65.              super.onProgressUpdate(progress);  

66.          }  

67.    

68.          @Override  

69.          protected void onPostExecute(String result) {  

70.              //doInBackground返回时触发,换句话说,就是doInBackground执行完后触发  

71.              //这里的result就是上面doInBackground执行后的返回值,所以这里是"执行完毕"  

72.              setTitle(result);  

73.              super.onPostExecute(result);  

74.          }  

75.            

76.      }  

77.  }  

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值