我似乎无法弄清楚为什么我的广播接收器不起作用。我希望收到传入的短信。
我没有在清单中声明广播接收器。我以编程方式注册它们。
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter filter = new IntentFilter(SMS_RECEIVED_ACTION);
filter.setPriority(999);
this.registerReceiver(smsListener, filter);
我的广播接收器是活动中定义的
public BroadcastReceiver smsListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(SMS_RECEIVED_ACTION)) {
System.out.println("In broadcast receiver");
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
System.out.println("SMS Message from: " + msg_from);
}
}catch(Exception e){
System.out.println("Error when receiving a message");
}
}
}
}
};
非常感谢任何想法。