I am working on a BlackBerry App that sends a message to the server when the battery level reaches 10%. This is implemented by calling getBatteryStatus()
method in the constructor where getBatteryStatus()
does the following:
public static void getBatteryStatus() {
timerBattery = new Timer();
taskBattery = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
if (DeviceInfo.getBatteryLevel()==10) {
try{
String freeText="Battery level at 10%";
sendBatteryStatus(freeText);
}catch(Exception e){}
}
}
});
}
};
timerBattery.scheduleAtFixedRate(taskBattery, 0, 20000);
}
The sendBatteryStatus
sends the message to the server and cancels the timer. This in effect has sent the message once to the server as requested.
However, what if the user starts charging its handset with the App running as it was (without the constructor being called again)? How will the timer then restart? How will I be able to send the message to the server again next time?
What is the best mechanism to prevent sending multiple messages of battery level at 10% and in effect send a message ONLY once followed by messages being sent again when the battery level is at 10% the next time?
If I do not cancel the timer once the message is sent, the message to the server is sent more than once.