import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; public class AndroidLuckyActivity extends Activity { private TextView textView; private Button button_start; private Button button_end; private Boolean begined = false; private Timer timer; private Handler handler; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); handler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if(begined == true) { textView.setText("" +msg.what); } else if(begined == false) { textView.setText("" + msg.what); timer.cancel(); //Timer停止 } } }; } void init() { textView = (TextView)this.findViewById(R.id.tv); button_start = (Button)this.findViewById(R.id.btn_start); button_end = (Button)this.findViewById(R.id.btn_end); button_start.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub begined = true; button_start.setEnabled(false); button_end.setEnabled(true); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Message message = new Message(); message.what = (int) (Math.random() * 999 + 100); handler.sendMessage(message); } }, 1000, 30); //从1000ms即1s开始,30ms为数字改变周期 } }); button_end.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub begined = false; button_start.setEnabled(true); button_end.setEnabled(false); } }); } }
运行图: