掃盲:sticky broadcast是什么,有什么作用?
中文名:粘性廣播 又有人認為是一直不斷的發(fā)廣播,其實不是,想想也知道,一直不斷的發(fā)廣播這種**機制是Google工程師能想出來的機制么。
google官方的解釋是:
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 assendBroadcast(Intent).
You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission,SecurityException will be thrown.
大概的意思是說: 發(fā)出的廣播會一直滯留(等待),以便有人注冊這則廣播消息后能盡快的收到這條廣播。其他功能與sendBroadcast相同。但是使用sendStickyBroadcast 發(fā)送廣播需要獲得BROADCAST_STICKY permission,如果沒有這個permission則會拋出異常。
Android系統(tǒng)在發(fā)送完broadcast后才被注冊的broadcastreceiver無法接收到在注冊前發(fā)送的broadcast,但是可以接收到該receiver在注冊前發(fā)送的sticky broadcast.
那么此時我們就知道了,我們的充電狀態(tài)廣播不是一直發(fā)的,我們能放心的不做重復判斷了。(真的么?事實上還得做重復判斷,如果我們想給用戶帶來良好的體驗)
如何獲取充電狀態(tài)?
private BroadcastReceiver mbatteryReceiver=new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action =intent.getAction();
if(Intent.ACTION_BATTERY_CHANGED.equals(action)) {
int status=intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN);
if(status==BatteryManager.BATTERY_STATUS_CHARGING){
Toast.makeText(getActivity(), "充電中!",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getActivity(), "未充電",Toast.LENGTH_SHORT).show();
}
}
}
};
mContext.registerReceiver(mbatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
unregisterReceiver(mbatteryReceiver);
謝謝大家閱讀,如有幫助,來個喜歡或者關(guān)注吧!
本文作者:Anderson/Jerey_Jobs
簡書地址:[Anderson大碼渣][1]
github地址:[Jerey_Jobs][2]
[1]: http://www.itdecent.cn/users/016a5ba708a0/latest_articles
[2]: https://github.com/Jerey-Jobs