3. 需要与UI交互的应用程序子线程消息模型
前面说过,我们开发应用程序的时候,经常中需要创建一个子线程来在后台执行一个特定的计算任务,而在这个任务计算的过程中,需要不断地将计算进度或者计算结果展现在应用程序的界面中。典型的例子是从网上下载文件,为了不阻塞应用程序的主线程,我们开辟一个子线程来执行下载任务,子线程在下载的同时不断地将下载进度在应用程序界面上显示出来,这样做出来程序就非常友好。由于子线程不能直接操作应用程序的UI,因此,这时候,我们就可以通过往应用程序的主线程中发送消息来通知应用程序主线程更新界面上的下载进度。因为类似的这种情景在实际开发中经常碰到,Android系统为开发人员提供了一个异步任务类(AsyncTask)来实现上面所说的功能,即它会在一个子线程中执行计算任务,同时通过主线程的消息循环来获得更新应用程序界面的机会。
为了更好地分析AsyncTask的实现,我们先举一个例子来说明它的用法。在前面一篇文章Android系统中的广播(Broadcast)机制简要介绍和学习计划中,我们开发了一个应用程序Broadcast,其中使用了AsyncTask来在一个线程在后台在执行计数任务,计数过程通过广播(Broadcast)来将中间结果在应用程序界面上显示出来。在这个例子中,使用广播来在应用程序主线程和子线程中传递数据不是最优的方法,当时只是为了分析Android系统的广播机制而有意为之的。在本节内容中,我们稍微这个例子作一个简单的修改,就可以通过消息的方式来将计数过程的中间结果在应用程序界面上显示出来。
- package shy.luo.counter;
-
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.os.AsyncTask;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class Counter extends Activity implements OnClickListener {
- private final static String LOG_TAG = "shy.luo.counter.Counter";
-
- private Button startButton = null;
- private Button stopButton = null;
- private TextView counterText = null;
-
- private AsyncTask<Integer, Integer, Integer> task = null;
- private boolean stop = false;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- startButton = (Button)findViewById(R.id.button_start);
- stopButton = (Button)findViewById(R.id.button_stop);
- counterText = (TextView)findViewById(R.id.textview_counter);
-
- startButton.setOnClickListener(this);
- stopButton.setOnClickListener(this);
-
- startButton.setEnabled(true);
- stopButton.setEnabled(false);
-
-
- Log.i(LOG_TAG, "Main Activity Created.");
- }
-
-
- @Override
- public void onClick(View v) {
- if(v.equals(startButton)) {
- if(task == null) {
- task = new CounterTask();
- task.execute(0);
-
- startButton.setEnabled(false);
- stopButton.setEnabled(true);
- }
- } else if(v.equals(stopButton)) {
- if(task != null) {
- stop = true;
- task = null;
-
- startButton.setEnabled(true);
- stopButton.setEnabled(false);
- }
- }
- }
-
- class CounterTask extends AsyncTask<Integer, Integer, Integer> {
- @Override
- protected Integer doInBackground(Integer... vals) {
- Integer initCounter = vals[0];
-
- stop = false;
- while(!stop) {
- publishProgress(initCounter);
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- initCounter++;
- }
-
- return initCounter;
- }
-
- @Override
- protected void onProgressUpdate(Integer... values) {
- super.onProgressUpdate(values);
-
- String text = values[0].toString();
- counterText.setText(text);
- }
-
- @Override
- protected void onPostExecute(Integer val) {
- String text = val.toString();
- counterText.setText(text);
- }
- };
- }
这个计数器程序很简单,它在界面上有两个按钮Start和Stop。点击Start按钮时,便会创建一个CounterTask实例task,然后调用它的execute函数就可以在应用程序中启动一个子线程,并且通过调用这个CounterTask类的doInBackground函数来执行计数任务。在计数的过程中,会通过调用publishProgress函数来将中间结果传递到onProgressUpdate函数中去,在onProgressUpdate函数中,就可以把中间结果显示在应用程序界面了。点击Stop按钮时,便会通过设置变量stop为true,这样,CounterTask类的doInBackground函数便会退出循环,然后将结果返回到onPostExecute函数中去,在onPostExecute函数,会把最终计数结果显示在用程序界面中。
在这个例子中,我们需要注意的是:
A. CounterTask类继承于AsyncTask类,因此它也是一个异步任务类;
B. CounterTask类的doInBackground函数是在后台的子线程中运行的,这时候它不可以操作应用程序的界面;
C. CounterTask类的onProgressUpdate和onPostExecute两个函数是应用程序的主线程中执行,它们可以操作应用程序的界面。
关于C这一点的实现原理,我们在后面会分析到,这里我们先完整地介绍这个例子,以便读者可以参考做一下实验。
本文转自 Luoshengyang 51CTO博客,原文链接:http://blog.51cto.com/shyluo/966881,如需转载请自行联系原作者
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。