CalvinWylie
CalvinWylie

Reputation: 143

How to pass the application context into a broadcast receiver while keeping the constructor empty

I'm currently working on a Live Wallpaper which need to keep track of the number of unread SMSs. When an SMS is received I update the SMSCount like this:

@Override
public void onReceive(Context context, Intent intent) {
    final Uri SMS_INBOX = Uri.parse("content://sms/inbox");

    Cursor c = context.getContentResolver().query(SMS_INBOX,
                                                  null,
                                                  "read = 0",
                                                  null,
                                                  null);
    mSMSCount = c.getCount();
    c.close();
}

which work fine. However, the value is updated only when a message is received so before that it gives an incorrect value (SMSCounts initialised value). So to initialise SMSCount to the right value I would have to initialise it with the above code. The problem being that it requires a context. When I try and pass the application context into the Broadcast receiver's constructor I get a "no empty constructor" exception.

Upvotes: 1

Views: 1774

Answers (3)

abhi
abhi

Reputation: 759

You can add parameterised constructor as well as default constructor.

Upvotes: 0

Marcio Covre
Marcio Covre

Reputation: 4556

OK, First things first, BroadcastReceiver is intended to receive a notification and alert someone, not to stay running, so if you have code outside onReceive your doing wrong.

From your question your doing more thing to need a Context on the constructor of your BroadcastReceiver.

My sugestion is to move all this code from onReceive to an IntentService, this service will start, do the lookup on the database and call to update the count, no instance variable because the service will end afterwards.

Then when starting your program you call this IntentService to show the unread count and also on the BroadcastReceiver you only call the IntentService.

Upvotes: 0

rennoDeniro
rennoDeniro

Reputation: 928

Just go ahead and add an empty constructor to your class as well as the constructor you are currently passing a context into, So in other words, add a constructor that takes no arguments.

Upvotes: 1

Related Questions