我需要从14:45到16:15运行timer
。
这是我的代码:
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
//new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
new SimpleDateFormat(" HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
//Calendar cal = Calendar.getInstance();
//cal.setTime(new Date());
final int hour = calendar.get(Calendar.HOUR_OF_DAY);
final int minute = calendar.get(Calendar.MINUTE);
System.out.println("HOUR:"+hour);
System.out.println("MINUTE:"+minute);
runOnUiThread(new Runnable(){
@Override
public void run() {
//135
if( hour >= 14 && hour <= 17) {
if (minute >= 45 && minute <= 59 || minute >= 00 && minute <=59 || minute >= 00 && minute <= 15 ) {
textCounter.setText(strDate);
} else {
timer.cancel();
}
}else{
timer.cancel();
}
}});
}
}
}
但是timer
总是在运行。
我错了什么?
有人可以帮助我吗?
感谢