sticky INTENT

銳湃發表於2015-08-31

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充電的狀態下,適當降低更新頻率,而如果是在非充電的時候,您應當將更新頻率降到最低的情況,以合理利用電量。

@Override  
    protected void onResume() {  
        // TODO Auto-generated method stub  
        super.onResume();  
        registerReceiver(mReceiver, mIntentFilter);  
    }  
      
    @Override  
    protected void onPause() {  
        // TODO Auto-generated method stub  
        super.onPause();  
        unregisterReceiver(mReceiver);  
    }  

在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).


轉自:http://blog.csdn.net/g_rrrr/article/details/7998963

相關文章