Android應(yīng)用組件主要由Activity、Service、Broadcast Receivers、Intent、Content Providers、AndroidManifest等構(gòu)成。其中Activity是與用戶直接交互UI組件;Service是運(yùn)行在后臺(tái)、用戶不可見的服務(wù)組件,今天給大家介紹的Broadcast Receivers 則是進(jìn)行系統(tǒng)消息廣播的廣播組件。
廣播接收器(Broadcast Receivers)是用來接收或者響應(yīng)廣播、通告的一個(gè)應(yīng)用組件,它與通知管理器密切相關(guān)。當(dāng)時(shí)區(qū)發(fā)生改變、電量不足、工作語言發(fā)生改變等事件發(fā)生時(shí),注冊(cè)相應(yīng)廣播接收器的應(yīng)用將會(huì)收到這些信息。
所有的廣播接收器都需要基于android.content.BroadcastReceiver基類。通過Context.registerReceiver()方法,開發(fā)者可以動(dòng)態(tài)地注冊(cè)廣播接收器。
定義接收的廣播的方式如下:
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(mIntentReceiver, filter);
廣播接收器的實(shí)現(xiàn)如下:
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED)
|| action.equals(Intent.ACTION_DATE_CHANGED)
|| action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
……
}
}
};
在調(diào)用組件被銷毀時(shí),必須銷毀廣播接收器,其方法如下:
protected void onPause()
{
super.onPause();
unregisterReceiver(mIntentReceiver);
}
當(dāng)然在AndroidManifest.xml文件中,也可以定義相應(yīng)的廣播接收器。其方法如下:
< receiver android:name="com.android.camera.CameraButtonIntentReceiver">
< intent-filter>
< action android:name="android.intent.action.CAMERA_BUTTON"/>
< /intent-filter>
< /receiver>
在目前的實(shí)現(xiàn)中,廣播分為兩種類型:標(biāo)準(zhǔn)廣播(Normal broadcasts)、順序廣播(Ordered broadcasts)。
標(biāo)準(zhǔn)廣播指廣播是完全異步的,所有的接收器處于無序的運(yùn)行狀態(tài)。這類廣播通過Context.sendBroadcast()方法發(fā)送。
順序廣播則按照一定的優(yōu)先級(jí)進(jìn)行廣播,高優(yōu)先級(jí)的接收器向低優(yōu)先級(jí)的接收器轉(zhuǎn)播廣播。如果需要,高優(yōu)先級(jí)的接收器也可以拋棄廣播,從而切斷低優(yōu)先級(jí)的接收器收到廣播的可能,在同一優(yōu)先級(jí)的接收器,收到廣播的順序則是隨機(jī)的。順序廣播通過Context.sendOrderedBroadcast()方法發(fā)送。