地址:
http://book.51cto.com/art/201211/363310.htm
方法postDelayed的作用是延迟多少毫秒后开始运行,而removeCallbacks方法是删除指定的Runnable对象,使线程对象停止运行。
方法声明如下:
- public final boolean postDelayed (Runnable r, long delayMillis)
其中参数Runnable r在Handler对象所运行的线程中执行。
创建名称为handler2的Android项目,Main.java的核心代码如下:
程序运行后单击button1按钮开始循环,count累加1,运行结果如图6.41所示
- public class Main extends Activity {
- private Button button1;
- private Button button2;
- private Handler handler = new Handler();
- private int count = 0;
- private Runnable runnableRef = new Runnable() {
- public void run() {
- Log.v("2", Thread.currentThread().getName());
- count++;
- Log.v("!", "count=" + count);
- handler.postDelayed(runnableRef, 1000);
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Log.v("1", Thread.currentThread().getName());
- button1 = (Button) this.findViewById(R.id.button1);
- button2 = (Button) this.findViewById(R.id.button2);
- button1.setOnClickListener(new OnClickListener() {
- public void onClick(View arg0) {
- Thread thread = new Thread(runnableRef);
- thread.start();
- Log.v("!!!!!!!!!!!!!", "end");
- }
- });
- button2.setOnClickListener(new OnClickListener() {
- public void onClick(View arg0) {
- handler.removeCallbacks(runnableRef);
- }
- });
- }
- }