在android中广播分为2种,一种常驻型广播,另一种就是非常驻型广播。二者的区别就在于程序关闭后广播是否还存在。
常驻型广播在android程序中的AndroidManifest.xml中进行注册
声明了一个针对收到短信的常驻型广播,如
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>非常驻型广播一般都在代码中注册,使用registerReceiver进行注册,使用unregisterReceiver进行销毁
注册
SMSReceiver smsReceiver = new SMSReceiver();
IntentFilter filter = new IntentFilter(); filter.addAction("android.provider.Telephony.SMS_RECEIVED");logo.this.registerReceiver(smsReceiver, filter);销毁
SMSReceiver smsReceiver = new SMSReceiver();
logo.this.unregisterReceiver(smsReceiver);广播代码:
public class SMSReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub System.out.println("receive message"); Bundle bundle = intent.getExtras(); Object[] myOBJpdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[myOBJpdus.length]; System.out.println(messages.length); for (int i = 0; i<myOBJpdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]); Date date = new Date(messages[i].getTimestampMillis()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String mobile = messages[i].getOriginatingAddress();//发送短信的手机号码 String time = format.format(date); //得到发送时间 String content = messages[i].getDisplayMessageBody(); System.out.println("手机号码=" + mobile + "发送时间 =" + time + "发送内容=" + content); } }}