I register a BroadcastReceiver for android.provider.Telephony.SMS_RECEIVED
.
Sometimes the BroadcastReceiver onReceive
is called twice on the same SMS.
Why is that?
what am I doing wrong?
private void initSmsReceivers() {
smsReceiver = new SmsReceiver();
getActivity().registerReceiver(smsReceiver,
new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
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]);
// str += "SMS from " + msgs[i].getOriginatingAddress();
// str += " :";
str += msgs[i].getMessageBody().toString();
}
// ---display the new SMS message---
String output = CryptoUtils.decrypt(str);
Toast.makeText(context, output, Toast.LENGTH_LONG).show();
try {
parsemessage(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON2", e.toString());
}
}
}
}
Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.
Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.
onReceive. This method is called when the BroadcastReceiver is receiving an Intent broadcast. During this time you can use the other methods on BroadcastReceiver to view/modify the current result values.
It could be the case that you are registering the broadcast receiver both programatically, and statically. So make sure that initSmsReceivers
is called exactly once, and that in your manifest you are not re-registering that receiver!
Here's how you statically register a receiver for sms in the manifest:
<receiver
android:name="your.package.SmsReceiver"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS" >
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With