sticky INTENT

BatteryManager 会发送“sticky”类型的系统广播,在 Intent 中包括了当前的电池电量状态和充电状态等信息。

因为电池状态的广播类型是 “sticky”类型的,所以我们不需要注册相应的BroadcastReceiver。只需要在调用 registerReceiver 的时候传递空参数null就可以,然后函数的返回值 intent 中就包括了当前电池状态的各种信息。

当然您也可以传递一个自定义的 BroadcastReceiver ,在后面的章节里面有介绍,不过实际上也是没有什么必要的。

示例代码:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

从返回的 Intent 中我们可以获得当前的充电状态和充电类型,是通过USB,还是AC充电器?

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;

通常情况下,在AC充电器的情况下,您可以最大化应用程序的更新频率,如果是在USB充电的状态下,适当降低更新频率,而如果是在非充电的时候,您应当将更新频率降到最低的情况,以合理利用电量。


  1.   @Override  
  2.     protected void onResume() {  
  3.         // TODO Auto-generated method stub  
  4.         super.onResume();  
  5.         registerReceiver(mReceiver, mIntentFilter);  
  6.     }  
  7.       
  8.     @Override  
  9.     protected void onPause() {  
  10.         // TODO Auto-generated method stub  
  11.         super.onPause();  
  12.         unregisterReceiver(mReceiver);  
  13.     } 
在ReceiverActivity里是通过代码来注册Recevier而不是在Manifest里面注册的。所以通过sendBroadcast中发出的intent在ReceverActivity不处于onResume状态是无法接受到的,即使后面再次使其处于该状态也无法接受到。而sendStickyBroadcast发出的Intent当ReceverActivity重新处于onResume状态之后就能重新接受到其Intent.这就是the Intent will be held to be re-broadcast to future receivers这句话的表现。就是说sendStickyBroadcast发出的最后一个Intent会被保留,下次当Recevier处于活跃的时候,又会接受到它。


What is the difference between sendStickyBroadcast and sendBroadcast in Android?

Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

你可能感兴趣的:(null)