Search code examples
androidbroadcastreceiversmsintentfilter

Can't seem to register Broadcastreceiver dynamically


I'm pretty new to android, and I've been trying to register my Broadcastreceiver dynamically so I could receive smss , but I just can't seem to make it work, here's my code:

public class MainActivity extends AppCompatActivity {

BroadcastReceiver receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "Hellllo", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(receiver,filter);
}

The "hello" Toast wont pop up so I'm assuming the receiver was not registered

I put this permissions in my manifest:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

What am i missing ?


Solution

  • We determined in comments that the SMS_RECEIVED broadcast was being intercepted and aborted by another app. This was possible in Android prior to KitKat (API 19), but it is not in versions since.

    The solution was to set the priority on the IntentFilter instance to 999, using the IntentFilter#setPriority() method.

    Please note, however, that it would still be possible for another app to abort the broadcast before yours receives it. Though the docs say that Receivers with IntentFilters at the same priority will be delivered the broadcast in an arbitrary order, it usually pans out that they're delivered in the order that the apps were installed. Furthermore, it is possible for some apps - e.g., system apps, pre-installed apps, etc. - to have their priority higher than 999, which is the maximum practical value for your app.