package cn.com.sxp;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

// Handler基本概念: Handler主要用于异步消息的处理:当发出一个消息之后,首先进入一个消息队列,发送消息的函数即刻返回,而另外一个部分逐个的在消息队列中将消息取出,然后对消息进行出来,就是发送消息和接收消息不是同步的处理。 这种机制通常用来处理相对耗时比较长的操作。
// 使用一个例子简单的来介绍一下Handler。

public class HandlerActivity extends Activity {
private Button startButton;
private Button endButton;

// 创建一个handler对象,由于是在主UI线程中创建的,因此这个handler应该是依附在该UI线程上,为该线程分配各队列,将子线程传来的消息、子线程等放在这个队列中,并且一个个执行
Handler handler = new Handler();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 可以在界面上展示了,但是只有界面元素,没有联系到后台具体的变量,因此没法将用户的交互传递到后台,只是一具空壳
setContentView(R.layout.main);

// 将界面元素与后台变量联系起来,从而系统可以处理用户的交互,不再是一具空壳
startButton = (Button) findViewById(R.id.startButton);
endButton = (Button) findViewById(R.id.endButton);

// 这里也有人叫注册
startButton.setOnClickListener(new StartButtonListener());
endButton.setOnClickListener(new EndButtonListener());

// 取得当前UI线程的号与名字
Log.d("onCreate()","UI线程的ID号: " + Thread.currentThread().getId());
Log.d("onCreate","UI线程的名字: " + Thread.currentThread().getName());
}

class StartButtonListener implements OnClickListener {
public void onClick(View v) {
// Causes the Runnable r to be added to the message queue. The
// runnable will be run on the thread to which this handler is
// attached. 应该是加入队列后立即执行
handler.post(updateThread);
}
}

class EndButtonListener implements OnClickListener {
public void onClick(View v) {
// Remove any pending posts of Runnable r that are in the message
// queue.
handler.removeCallbacks(updateThread);
}

}


Runnable updateThread = new Runnable() {
// 要执行的操作写在线程对象的run方法当中
public void run() {
Log.d("in updateThread run()","updateThread 线程的ID是: "
+ Thread.currentThread().getId());
Log.d("in updateThread run()","updateThread 线程的名字是: "
+ Thread.currentThread().getName());
// Causes the Runnable r to be added to the message queue, to be run
// after the specified amount of time elapses. The runnable will be
// run on the
// thread to which this handler is attached.
handler.postDelayed(updateThread, 3000);
}
};
}

所有需要注释阐明的都在代码中提过。运行截图如下:

打印的日志:

 

当我点击了“start”button后,日志打印如下:

 

当再次点击“end”按钮后,便会结束这一切

 

 

 

posted on 2012-01-15 12:17  C语言答疑课堂  阅读(171)  评论(0编辑  收藏  举报