2013-04-11 97 views
1

我正在使用BlackBerry App,当电池电量达到10%时向服务器发送消息。这是通过调用getBatteryStatus()方法在getBatteryStatus()执行以下操作的构造实施:当电池电量达到10%时开始/取消计时器

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); 
} 

sendBatteryStatus将消息发送到服务器,并取消定时器。这实际上已经根据请求将消息一次发送到服务器。

但是,如果用户开始使用App运行它的手机充电(如果没有再次调用构造函数),该怎么办?计时器如何重启?我将如何能够再次将消息发送到服务器?

什么来防止在10%,在效果发送消息只有一次,随后的消息被再次发送当电池电量在接下来的时间10%发送电池电量的多个消息的最佳机制是什么?

如果在发送消息后我不取消计时器,则会向服务器发送多次消息。

回答

3

我实际上认为如果你完全摆脱了你的计时器,你会更好。我不认为计时器会有效地给你所有你想要的东西。

幸运的是,BlackBerry有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()方法添加到类,或通过该类谁实现sendBatteryStatus()方法的对象。

注:我也建议你寄送通知到服务器的主线程上。你不显示sendBatteryStatus()的实现,所以也许你已经是。但是,如果没有,请使用后台线程来通知您的服务器,所以用户界面不会被冻结。