BroadcastReceiver用於接收廣播Intent,廣播Intent的發送是通過調用Context.sendBroadcast()、Context.sendOrderedBroadcast()來實現的。通常一個廣播Intent可以被訂閱了此Intent的多個廣播接收者所接收
0.要實現一個廣播接收者方法如下:
(1)第一步:繼承BroadcastReceiver,並重寫onReceive()方法。
- public class IncomingSMSReceiver extends BroadcastReceiver
- {
- @Override public void onReceive(Context context, Intent intent){ }
- }
- public class IncomingSMSReceiver extends BroadcastReceiver
- {
- @Override public void onReceive(Context context, Intent intent){ }
- }
(2)第二步:訂閱感興趣的廣播Intent,訂閱方法有兩種:
第一種:使用代碼進行訂閱
- IntentFilter filter = new IntentFilter("Android.provider.Telephony.SMS_RECEIVED");
- IncomingSMSReceiver receiver = new IncomingSMSReceiver();
- registerReceiver(receiver, filter);
- IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
- IncomingSMSReceiver receiver = new IncomingSMSReceiver();
- registerReceiver(receiver, filter);
第二種:在AndroidManifest.xml文件中的<application>節點裡進行訂閱:
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
- </intent-filter>
- </receiver>
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
- </intent-filter>
- </receiver>
1.除了短信到來廣播Intent,Android還有很多廣播Intent,如:開機啟動、電池電量變化、時間已經改變等廣播Intent。
(1)接收電池電量變化廣播Intent ,在AndroidManifest.xml文件中的<application>節點裡訂閱此Intent:
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BATTERY_CHANGED"/>
- </intent-filter>
- </receiver>
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BATTERY_CHANGED"/>
- </intent-filter>
- </receiver>
(2)接收開機啟動廣播Intent,在AndroidManifest.xml文件中的<application>節點裡訂閱此Intent:
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED"/>
- </intent-filter>
- </receiver>
- <receiver android:name=".IncomingSMSReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED"/>
- </intent-filter>
- </receiver>
並且要進行權限聲明:
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>