Jingyue Hu
Jingyue Hu

Reputation: 23

How to pass data from activity to broadcastReceiver?

i have code that calls a broadcast receiver, in the receiver, i try to get the extra data from the intent, but it's null.

so,

     Intent intent = new Intent(MainActivity.this, CallAlarm.class);
                          intent.putExtra("medicine", "kkk");

                          PendingIntent sender=PendingIntent.getBroadcast(
                                  MainActivity.this,0, intent, 0);

                          AlarmManager am;
                          am = (AlarmManager)getSystemService(ALARM_SERVICE);
                          am.set(AlarmManager.RTC_WAKEUP,
                                 c.getTimeInMillis(),
                                 sender
                                );

and in the BroadcastReceiver.onReceiver(),

    String name = i.getStringExtra("medicine");

but medicine is null. what am i missing?

Upvotes: 2

Views: 1909

Answers (2)

user1810931
user1810931

Reputation: 658

I was trying the above code, I get value always null. My broadcast receiver starts on bootup so apart from the above code I also add intent.setAction("android.intent.action.BOOT_COMPLETED");

Still it gives me null.

Upvotes: 0

Lalit Poptani
Lalit Poptani

Reputation: 67286

Just create the PendingIntent with flag PendingIntent.FLAG_UPDATE_CURRENT,

 Intent intent = new Intent(MainActivity.this, CallAlarm.class);
 intent.putExtra("medicine", "kkk");
 PendingIntent sender=PendingIntent.getBroadcast(
                                  MainActivity.this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

This will enable you to pass the data to the BroadCastReceiver.

Upvotes: 3

Related Questions