Search code examples
androidlocalbroadcastmanager

Android - LocalBroadcastManager for SMS interception not firing


I've got an JavascriptInterface method that registers a LocalBroadcastManager listening to received SMS's. When an SMS arrives the onReceive method doesn't get called.

public void UIregisterSMSSource(String number) {
    LocalBroadcastManager.getInstance(this)
        .registerReceiver(mMessageReceiver, new IntentFilter(ACTION_SMS_RECEIVE));
}

/**
* SMS Receiver
*/
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_SMS_RECEIVE)) {
            StringBuilder buf = new StringBuilder();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Bundle extras = intent.getExtras();
                Object[] pdus = (Object[]) extras.get("pdus");
                for (int i = 0; i < pdus.length; i++) {
                    SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    String sender = SMessage.getOriginatingAddress();
                    String body = SMessage.getMessageBody().toString();
                    Log.d(TAG, "[SMS] onReceive by " + sender + ". Content - " + body);
                    // Save preferences of the activation code

                }
            }
        }
    }
};

This is the ACTION_SMS_RECEIVE variable:

private static final String ACTION_SMS_RECEIVE = "android.provider.Telephony.SMS_RECEIVED";

I've tested this before as BroadcastaReceiver and it worked. I removed the receiver from the manifest too which I don't know if it's right.

Do I need to configure something more? On the examples I've came across there's no further configuration needed.

Thanks in advance.


Solution

  • Receiver mMessageReceiver can only listen the intent which sent via LocalBroadcastManager.sendBroadcast(intent).

    Here, intent with android.provider.Telephony.SMS_RECEIVED action, is being raised by system (not using LocalBroadcastManager.sendBroadcast(intent)), so your app does not listen to this intent.

    Your previous approach was correct, and you can continue on that logic.


    You can read a detailed example of LocalBroadcastManager to make clear your doubts about its working flow.