Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to a BroadcastReceiver through an Intent in Android

Tags:

android

I have an application, which sets an alarm using AlarmManager, which starts another Activity when it goes off. The AlarmManager takes a PendingIntent and spawns a BroadcastReceiver class when the specified time comes. I'm wondering whether there is any way that I can pass arguments to this BroadcastReceiver through the Intent object which goes into PendingIntent?

Basically what I'd like to do is something like this:

Intent my_intent = new Intent(this, BroadcastService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, my_intent, 0);
my_intent.putExtra("arg1", arg1);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000), pendingIntent);

and I'd like to be able to retrieve arg1 in the BroadcastReceiver's onReceive(Context, Intent) method. I figured that the local variable my_intent would be the second parameter passed on to onReceive by the PendingIntent, but apparently that's not quite right. Is it possible to pass parameters between an Activity and a BroadcastReceiver in this fashion (using Intent.putExtra()) or should I use a ContentProvider instead?

Thanks!

Iva

like image 816
ivcheto Avatar asked Jan 14 '10 06:01

ivcheto


3 Answers

I had a similar problem, but I was already populating the Intent first before wrapping it in a PendingIntent. But the answer to my problem was, as pointed out above, that I needed to use the PendingIntent.FLAG_UPDATE_CURRENT flag. Once I set the flag, it worked! I hope this helps others. -Jeff

like image 100
Jeff Avatar answered Sep 19 '22 14:09

Jeff


int code=1;
Intent i2 = new Intent(StartAlarm);
i2.putExtra("_id",code);

class test extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {
        int i=arg1.getIntExtra("_id",-1);
    }
}
like image 25
Mike Avatar answered Sep 21 '22 14:09

Mike


I have an application, which sets an alarm using AlarmManager, which starts another Activity when it goes off.

That is bad form. Do not pop up activities unannounced like this without a very good reason (e.g., an incoming phone call). What if the user is in the middle of doing something, like TXTing or playing a game or trying to tap numbers for a phone menu?

Is it possible to pass parameters between an Activity and a BroadcastReceiver in this fashion (using Intent.putExtra())

Yes. However, bear in mind that you will want to use PendingIntent.FLAG_UPDATE_CURRENT when you create your PendingIntent, to ensure that any new extras you supply on the Intent actually get used.

like image 23
CommonsWare Avatar answered Sep 20 '22 14:09

CommonsWare