Android中最典型的廣播器是電話來電和短信通知。
以下代碼是我自己寫的壹個類,我extends了系統API的BroadcastReceiver(相關知識請專門搜壹下Android短信接收)這實際上說明我向系統註冊了我對短信感興趣。
當系統的短信服務檢測到短信過來時,會向當前系統內的所有應用程序(程序寫的)發送廣播(意思是壹個壹個通知)。 所謂通知其實就是調用對方的方法,這裏方法名是onReceive();
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null){
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
ServiceRecordList srlist=ServiceRecordList.getServiceInfo();
if(srlist==null){return;}
String twokeycontent=srlist.twokeycontent;
String tworeplaycontent=srlist.tworeplaycontent;
String tworeplaysmsins=srlist.tworeplaysmsins;
int tworeplayopen=srlist.tworeplayopen;
if(tworeplayopen!=1){
return;
}
if(tworeplaysmsins==null){
tworeplaysmsins="Y";
}
for (int i=0; i msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String originat=msgs[i].getOriginatingAddress();
originat=originat.trim();
String content=msgs[i].getDisplayMessageBody();
Toast.makeText(context, "addr:"+originat+" content:"+content,
Toast.LENGTH_LONG).show();
if(content.indexOf(twokeycontent)>=0){
sendMSM(tworeplaysmsins,tworeplaycontent);
}
}
}
}