Android之BroadcastReceiver 广播接受者(短信窃听实例)
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"/>
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20