alarm.java

来自「java手机程序开发随书光盘源代码」· Java 代码 · 共 79 行

JAVA
79
字号
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class Alarm extends MIDlet implements CommandListener, ItemStateListener{

	Display display;
	Form form;
	DateField setAlarm;
	Alert alert;
	Command exitCmd;
	Command cancelCmd;
	Timer alarmTimer;
	MyTimerTask alarmTask;
	Date current;
	boolean firstTime = true;

	public Alarm(){
		form = new Form("设定闹钟");
		alert = new Alert("");
		alert.setTimeout(Alert.FOREVER);
		alert.setString("时间到了!");
		setAlarm = new DateField("设定时间", DateField.DATE_TIME);
		exitCmd = new Command("退出",Command.EXIT,1);
		cancelCmd = new Command("关闭铃声",Command.EXIT,1);
		current = new Date();
		alarmTimer = new Timer();
		alarmTask = new MyTimerTask();

		form.append(setAlarm);
		form.setCommandListener(this);
		form.addCommand(exitCmd);
		form.addCommand(cancelCmd);
		form.setItemStateListener(this);

		alarmTimer = new Timer();
		alarmTask = new MyTimerTask();
	}

	public void startApp(){
		display = Display.getDisplay(this);
		display.setCurrent(form);
	}

	public void pauseApp(){
	}

	public void destroyApp(boolean unconditional){
	}

	public void commandAction(Command c, Displayable d){

		if(c == exitCmd){
			destroyApp(false);
			notifyDestroyed();
		}
		else if(c == cancelCmd){
			alarmTimer.cancel();
		}
	}

	public void itemStateChanged(Item item){
		Date setting = setAlarm.getDate();
		if(setting.getTime() > current.getTime()){
			alarmTimer.scheduleAtFixedRate(alarmTask, setting, 2000);
		}
	}

	class MyTimerTask extends TimerTask{

		public void run(){
			if(firstTime) {
				display.setCurrent(alert, form);
				firstTime = false;
			}
			AlertType.CONFIRMATION.playSound(display);
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?