事实上,我认为如果你完全去掉计时器,你会过得更好。我不认为计时器能有效地为你提供你想要的一切。
幸运的是,黑莓拥有
SystemListener
界面这样执行:
public final class BatteryListener implements SystemListener {
/** the last battery level we were notified of */
private int _lastLevel = 0;
/** the battery percentage at which we send an event */
private int _threshold = 10;
public BatteryListener() {
Application.getApplication().addSystemListener(this);
}
public void setThreshold(int value) {
_threshold = value;
}
/** call this to stop listening for battery status */
public void stopListening() {
Application.getApplication().removeSystemListener(this);
}
private boolean levelChanged(int status) {
return (status & DeviceInfo.BSTAT_LEVEL_CHANGED) == DeviceInfo.BSTAT_LEVEL_CHANGED;
}
public void batteryStatusChange(int status) {
if (levelChanged(status)) {
int newLevel = DeviceInfo.getBatteryLevel();
if (newLevel <= _threshold && _lastLevel > _threshold) {
// we have just crossed the threshold, with battery draining
sendBatteryStatus("Battery level at " +
new Integer(newLevel) + "%!");
}
_lastLevel = newLevel;
}
}
public void batteryGood() { /** nothing to do */ }
public void batteryLow() { /** nothing to do */ }
public void powerOff() { /** nothing to do */ }
public void powerUp() { /** nothing to do */ }
}
然后,只要你想让你的应用程序
开始
为您监控电池。如果电池电量降至10%,它将发送一条消息。如果用户稍后再次开始充电,然后停止充电,并且再次消耗超过10%,则会发送另一条服务器消息。
private BatteryListener listener;
和
listener = new BatteryListener(); // start monitoring
显然,在上面的课程中,您要么必须添加
sendBatteryStatus()
方法传递给类,或者向该类传递一个实现
发送电池状态()
方法
注:
我还建议你
不
将您的通知发送到主线程上的服务器。您没有显示的实现
发送电池状态()
,所以也许你已经是了。但如果没有,请使用后台线程通知您的服务器,这样UI就不会被冻结。