Register BroadcastReceiver For Incoming SMS

2019-02-09 12:00发布

How to Register BroadcastReceiver For blocking Incoming SMSs

    IntentFilter intentFilter = new IntentFilter(Intent."what should be here");
     ctx.registerReceiver(outgoingReceiver, intentFilter);

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-09 12:20

Try the following :

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

Hope this helps.

查看更多
Rolldiameter
3楼-- · 2019-02-09 12:29

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

查看更多
乱世女痞
4楼-- · 2019-02-09 12:30

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();
    }
}                
查看更多
劳资没心,怎么记你
5楼-- · 2019-02-09 12:39

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);
}
    }
查看更多
登录 后发表回答