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 sp开发者_运维知识库ecified 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
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
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);
}
}
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.
Yes, I think it is possible to pass any data of basic Java type and Serializable/Parceable types in the extras of an Intent wrapped around a PendingIntent and then retrieve them using the Intent instance passed to the onReceive of the Broadcastreceiver. Your approach looks okay to me.
What is the problem/error that you are getting? Is "arg1" instance Serializable?
精彩评论