Android之BroadcastReceiver 广播接受者(短信窃听实例)

BroadcastReceiver用于接收广播Intent,广播Intent的发送是通过调用Context.sendBroadcast()Context.sendOrderedBroadcast()来实现的。通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收

0.要实现一个广播接收者方法如下

(1)第一步:继承BroadcastReceiver,并重写onReceive()方法

  1. public class IncomingSMSReceiver extends BroadcastReceiver  
  2. {  
  3.   @Override public void onReceive(Context context, Intent intent){ }  
  4. }  
 
  1. public class IncomingSMSReceiver extends BroadcastReceiver  
  2. {  
  3.   @Override public void onReceive(Context context, Intent intent){ }  
  4. }  

(2)第二步:订阅感兴趣的广播Intent,订阅方法有两种

第一种:使用代码进行订阅

 
  1. IntentFilter filter = new IntentFilter("Android.provider.Telephony.SMS_RECEIVED");  
  2. IncomingSMSReceiver receiver = new IncomingSMSReceiver();  
  3. registerReceiver(receiver, filter);  
 
  1. IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");  
  2. IncomingSMSReceiver receiver = new IncomingSMSReceiver();  
  3. registerReceiver(receiver, filter);  

第二种:在AndroidManifest.xml文件中的<application>节点里进行订阅:

 
  1. <receiver android:name=".IncomingSMSReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.provider.Telephony.SMS_RECEIVED"/>  
  4.     </intent-filter>  
  5. </receiver>  
 
  1. <receiver android:name=".IncomingSMSReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.provider.Telephony.SMS_RECEIVED"/>  
  4.     </intent-filter>  
  5. </receiver>  

1.除了短信到来广播Intent,Android还有很多广播Intent,如:开机启动、电池电量变化、时间已经改变等广播Intent。

(1)接收电池电量变化广播Intent ,在AndroidManifest.xml文件中的<application>节点里订阅此Intent:
 
  1. <receiver android:name=".IncomingSMSReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.intent.action.BATTERY_CHANGED"/>  
  4.     </intent-filter>  
  5. </receiver>  
 
  1. <receiver android:name=".IncomingSMSReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.intent.action.BATTERY_CHANGED"/>  
  4.     </intent-filter>  
  5. </receiver>  

(2)接收开机启动广播Intent,在AndroidManifest.xml文件中的<application>节点里订阅此Intent:

 
  1. <receiver android:name=".IncomingSMSReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.intent.action.BOOT_COMPLETED"/>  
  4.     </intent-filter>  
  5. </receiver>  
 
  1. <receiver android:name=".IncomingSMSReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.intent.action.BOOT_COMPLETED"/>  
  4.     </intent-filter>  
  5. </receiver>  

并且要进行权限声明:

 
  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>  
 
  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>  

相关推荐