//Broadcase用法
<!--使用SMS_ACTION时需要在 manifest.xml中 添加用户权限 -->
1 <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
//发送广播的TestBCActivity,文件如下:
1 public class TestBCActivity extends Activity { 2 /** Called when the activity is first created. */ 3 private Button registerButton = null; 4 private Button unregisterButton = null; 5 private SMSReceiver smsReceiver = null; 6 7 private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED"; 8 @Override 9 public void onCreate(Bundle savedInstanceState) { 10 super.onCreate(savedInstanceState); 11 setContentView(R.layout.main); 12 registerButton = (Button)findViewById(R.id.registerButton); 13 registerButton.setOnClickListener(new RegisterButtonListener()); 14 unregisterButton = (Button)findViewById(R.id.unregisterButton); 15 unregisterButton.setOnClickListener(new UnregisterButtonListener()); 16 } 17 //绑定监听器 18 class RegisterButtonListener implements OnClickListener{ 19 @Override 20 public void onClick(View v) { 21 //生成一个BroadcastReceiver对象 22 smsReceiver = new SMSReceiver(); 23 //生成一个IntentFilter对象 24 IntentFilter filter = new IntentFilter(); 25 //为InterntFilter添加一个Action 26 filter.addAction(SMS_ACTION); 27 //将BroadcastReceiver对象注册到系统当中 28 TestBCActivity.this.registerReceiver(smsReceiver, filter); 29 } 30 } 31 //解除绑定监听器 32 class UnregisterButtonListener implements OnClickListener{ 33 @Override 34 public void onClick(View v) { 35 TestBCActivity.this.unregisterReceiver(smsReceiver); 36 } 37 } 38 }
//接收广播的 SMSReceiver
1 public class SMSReceiver extends BroadcastReceiver { 2 public SMSReceiver() { 3 super(); 4 } 5 @Override 6 public void onReceive(Context context, Intent intent) { 7 System.out.println("receive message !"); 8 //解析收到的信息具体内容 9 //接收Intent对象当中的数据, 10 Bundle bundle = intent.getExtras(); 11 //在Bundle对象当中有一个属性,为pdus,这个属性的值是一个Object数组 12 Object[] myOBJpdus = (Object[])bundle.get("pdus"); 13 //创建一个SmsMessage类型的数组 14 SmsMessage[] messages = new SmsMessage[myOBJpdus.length]; 15 System.out.println(messages.length); 16 for(int i = 0; i<myOBJpdus.length;i++) 17 { 18 //使用Object数组当中的对象创建SmsMessage对象 19 messages[i]= SmsMessage.createFromPdu((byte[])myOBJpdus[i]); 20 //调用SmsMessage对象的getDisplayMessageBody()方法,就可以得到消息的内容 21 System.out.println(messages[i].getDisplayMessageBody()); 22 } 23 } 24 }