My app needs to be able to receive SMS messages. It all works, but I get this lint warning:
BroadcastReceivers that declare an intent-filter for SMS_DELIVER or SMS_RECEIVED must ensure that the caller has the BROADCAST_SMS permission, otherwise it is possible for malicious actors to spoof intents.
How do I "ensure that the caller has the BROADCAST_SMS permission"?
In my manifest I have:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application ...>
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
My code:
public class SmsReceiver extends BroadcastReceiver {
public SmsReceiver() {}
@Override
public void onReceive(final Context context, final Intent intent) {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
final SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
// use currentMessage
}
}
}
}
A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.
To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().
Sending Broadcast message We can send Broadcast message using method context. sendBroadcast() .
Add android:permission="android.permission.BROADCAST_SMS"
to the opening <receiver>
tag.
Also, components are enabled by default, and the <intent-filter>
exports it, so you don't really need to explicitly include those attributes.
<receiver
android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
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