Home » Android » android – Register BroadcastReceiver For Incoming SMS

android – Register BroadcastReceiver For Incoming SMS

Posted by: admin June 15, 2020 Leave a comment

Questions:

How to Register BroadcastReceiver For blocking Incoming SMSs

    IntentFilter intentFilter = new IntentFilter(Intent."what should be here");
     ctx.registerReceiver(outgoingReceiver, intentFilter);
How to&Answers:

Try the following :

intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");

Hope this helps.

Answer:

You should check for the permission

if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.RECEIVE_SMS}, 0);
} else {
        // register sms receiver
        IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
        registerReceiver(smsReceiver, filter);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {

    } else {
        // register sms receiver
        IntentFilter filter = new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
        registerReceiver(smsReceiver, filter);
}
    }

Answer:

Register a receiver in your manifest with highest priority:

    <receiver android:name=".SmsReceiver"> 
        <intent-filter android:priority="9999"> 
            <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
        </intent-filter> 
    </receiver>        

Create BroadcastReceiver class:

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    }
}

Implement onReceive method:

Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey("pdus")) {
    Object[] pdus = (Object[]) bundle.get("pdus");
    SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[0]);
    String senderNumber = sms.getOriginatingAddress();
    if( senderIsInBlackList(senderNumber)) {
        abortBroadcast();
    }
}                

Answer:

Declare the receiver in your AndroidManifest.xml:

 <receiver
        android:name="com.example.YourSmsReceiver"
        android:exported="true" >
        <intent-filter android:priority="1000" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
 </receiver>

Hope this helps, Yaron