broadcastreceiver – Android BroadcastReciever – Concept-ThrowExceptions

Exception or error:

I tried to wrap my head around Android BroadcastReceiver but with no success. I’m trying to implement something simple:

  1. Listen to an incoming SMS
  2. Check if the number is saved
  3. If it is saved do something

So far I registered / created the BroadcastReceiver and I’m able to catch the incoming messages. I did this in the following way:

public class SmsReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {


        //do things

I registered the receiver in the Manifest file in the following way:


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

Everything fine until now.
But, and here is the big BUT: I also created a class called ‘UserManager’ with a few basic tasks, for example: adding a new user, deleting a user, checking if the user exists, etc.

I store the users in a HashMap (phoneNumber, Name).

My questions are:

  1. How can I pass an Object to my BroadcastReceiver? ( I want to be able to access the HashMap from the “UserManager” class)

  2. I found a lot of topics regarding BroadcastReceivers. Some of them said that there are a couple ways of declaring a broadcast receiver. For example you could do it the way I did ( declaring it in Manifest), or you could do something more uhm… context based? Like declaring it BroadcastReceiver br = new MyBroadcastReceiver() and registering intentFilters to it. What is the difference? Which one should I use?

  3. Is there something called “good practice”? What should I pay attention to? Do you know any material which explains clearly the different ways of using a broadcastReceiver?
How to solve:
  1. You can use dependency injection. Or just hold reference to a class in you Application, that can be accessed by getApplicationContext
  2. Difference is – for receivers declared in manifest you can receiver messages even if you app is in destroyed state. If you broadcast receiver is created manually, well, you must create it before message will be delivered. Also Android forces some restriction on receivers declared in manifest.

Leave a Reply

Your email address will not be published. Required fields are marked *