在Android实现广播接收


  本文标签:Android 广播接收者

  在Android使用过程中,如果你想窃听别人接收到的短信,达到你不可告人的目的,那么本节内容可以实现你的需求  。当系统收到短信时,会发出一个action名称为android.provider.Telephony.SMS_RECEIVED的广播Intent,该Intent存放了接收到的短信内容,使用名称“pdus”即可从Intent中获取短信内容  。这里面得到对象数组,数组是以二进制数组格式

  1. public class SmsBroadcastReceiver extends BroadcastReceiver {  
  2.         @Override  
  3.         public void onReceive(Context context, Intent intent) {  
  4.                 Object[] pduses=(Object[])intent.getExtras().get("pdus");  
  5.                 for(Object pdus: pduses){  
  6.                         byte[] pdusSms=(byte[])pdus;  
  7.                         SmsMessage smsMessage=SmsMessage.createFromPdu(pdusSms);  
  8.                         String mobile=smsMessage.getOriginatingAddress();//获得发短信手机  
  9.                         String content=smsMessage.getMessageBody();//获得短信内容  
  10.                         Date datenew Date(smsMessage.getTimestampMillis());//获得短信发送时间  
  11.                         SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  12.                         String sendDate=simpleDateFormat.format(date);  
  13.                 }  
  14.         }  
  15. }  
  16. 在AndroidManifest.xml文件中的<application>节点里对接收到短信的广播Intent进行订阅:  
  17. <receiver android:name=".IncomingSMSReceiver"> 
  18. <intent-filter><action android:name="android.provider.Telephony.SMS_RECEIVED"/>intent-filter>receiver> 
  19. 在AndroidManifest.xml文件中添加以下权限:  
  20. <uses-permission android:name="android.permission.RECEIVE_SMS"/> 
  21. <uses-permission android:name="android.permission.SEND_SMS"/> 

  广播接收者

  除了短信到来广播Intent,Android还有很多广播Intent,如:开机启动、电池电量变化、时间已经改变等广播Intent  。
 接收电池电量变化广播Intent ,在AndroidManifest.xml文件中的节点里订阅此Intent:  。

  1. <receiver android:name=".IncomingSMSReceiver"> 
  2.     <intent-filter> 
  3.          <action android:name="android.intent.action.BATTERY_CHANGED"/> 
  4.     intent-filter> 
  5. receiver> 
  6.  接收开机启动广播Intent,在AndroidManifest.xml文件中的<application>节点里订阅此Intent:  
  7. <receiver android:name=".IncomingSMSReceiver"> 
  8.     <intent-filter> 
  9.          <action android:name="android.intent.action.BOOT_COMPLETED"/> 
  10.     intent-filter> 
  11. receiver> 

  并且要进行权限声明:

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