即使我使用abortBroadcast(),我的广播接收器截获的短信也被发送到我的收件箱。只有当我使用unRegisterReceiver()时才会出现此问题。如果我不unRegister,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);
...
}
答案 0 :(得分:1)
一个有效的解决方案是使用延迟(甚至0毫秒工作!)来取消注册:
new Handler().postDelayed(new Runnable(){
public void run(){
unregisterReceiver(BR_smsreceiver);
}
},0);
答案 1 :(得分:0)
public void onPause() {
// TODO Auto-generated method stub
unregisterReceiver(BR_smsreceiver);
}