Java Reference
In-Depth Information
I save the details of how to use the push registry for incoming messages until Chapter 14
when I discuss the Wireless Messaging API in detail. For now, you just need to know that
the MIDlet alarm mechanism also operates through the same mechanism, with one
exception: MIDlets can only register for alarms through the push registry at runtime, not
via the manifest.
To register for an alarm, you use the PushRegistry.registerAlarm method, which is
available from the javax.microedition.io package. This method takes the name of a
MIDlet to which the alarm should be sent, along with the time at which the alarm should
fire. A MIDlet may have at most one active alarm; the registerAlarm method returns the
last scheduled launch time; to cancel the alarm, pass 0 for the time.
You should only use an alarm when an application is not running. When an appli-
cation is running, you should use the Timer and TimerTask classes provided by the MIDP
instead. The java.util.Timer class manages a single java.util.TimerTask subclass; to
use it, create a subclass of java.util.TimerTask that overrides its run method with the
code that must be performed. Then schedule the subclass's execution using the timer's
schedule method. Listing 4-2 shows the relationship between alarms and timers for a
simple MIDlet that notifies the user 15 seconds after it is launched, even if you termi-
nate the MIDlet before the notification appears.
Listing 4-2. Using Alarms and Timers Together
package com.apress.rischpater.alarmtimer;
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class AlarmTimerMidlet extends MIDlet implements CommandListener {
private Form infoForm;
private StringItem helloStringItem;
private Command exitCommand;
private Alert alarmAlert;
private long DELAY = 15 * 1000;
private Timer timer;
private MyTask task;
private long whenLaunched = new Date().getTime();
private String storeName = "AlarmTimerStore";
private RecordStore store;
 
Search WWH ::




Custom Search