即使我使用 abortBroadcast(),已被我的广播接收器截获的 SMS 仍被发送到我的收件箱。仅当我使用 unRegisterReceiver() 时才会出现此问题。如果我不取消注册,abortBroadcast 工作正常。关于如何中止然后成功注销的任何想法?这是代码:
在我的主要活动中,我声明了一个广播接收器对象:
SmsReceiver BR_smsreceiver = null;
然后我注册广播接收器并从主要活动的一个函数中发送一条短信:
public Boolean sendVerificationSms(String number) {
BR_smsreceiver = null;
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setMainActivityHandler(this);
IntentFilter fltr_smsreceived = new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver, fltr_smsreceived);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, "hi", null, null);
}
广播接收器拦截 SMS 并调用主要活动中的函数:
public class SmsReceiver extends BroadcastReceiver {
MainActivity main = null;
void setMainActivityHandler(MainActivity main){
this.main=main;
}
@Override
public void onReceive(Context context, Intent intent) {
Bundle pdusBundle = intent.getExtras();
Object[] pdus=(Object[])pdusBundle.get("pdus");
SmsMessage messages=SmsMessage.createFromPdu((byte[]) pdus[0]);
if(messages.getMessageBody().contains("hi")){
abortBroadcast();
main.verifyPhoneNumber("hi");
}
}
}
该函数注销广播接收器并进行一些处理:
public void verifyPhoneNumber(String number) {
unregisterReceiver(BR_smsreceiver);
...
}