作者:大傻vv_528 | 来源:互联网 | 2023-08-22 20:30
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文件中的节点里进行订阅:
- <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文件中的节点里订阅此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文件中的节点里订阅此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"/>