首页 > 代码库 > handler

handler

package mars.handler;

import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;

public class HandlerActivity extends Activity {     /** Called when the activity is first created. */  //声明两个按钮控件  private Button startButton = null;  private Button endButton = null;     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         //根据控件的ID得到代表控件的对象,并未这两个按钮设置相应的监听器         startButton = (Button)findViewById(R.id.startButton);         startButton.setOnClickListener(new StartButtonListener());         endButton = (Button)findViewById(R.id.endButton);         endButton.setOnClickListener(new EndButtonListener());             }     class StartButtonListener implements OnClickListener{

  @Override   public void onClick(View v) {    //调用Handler的post方法,将要执行的线程对象添加到队列当中    handler.post(updateThread);   }           }         class EndButtonListener implements OnClickListener{

  @Override   public void onClick(View v) {    handler.removeCallbacks(updateThread);   }           }     //创建一个Handler对象     Handler handler  = new Handler();     //将要执行的操作写在线程对象的run方法当中     Runnable updateThread =  new Runnable(){

  @Override   public void run() {    System.out.println("UpdateThread");    //在run方法内部,执行postDelayed或者是post方法    handler.postDelayed(updateThread, 3000);   }           }; }

handler