1

I am aware that to put values I can intent.putExtra(key, value) and to retrieve values we can intent.getStringExtra(key) but in following code its not behaving as expected. When retrieving values, I am getting NUllPointer, printLn needs a message.

Code where I am setting values:

public void SetAlarm(Context context, int seconds, String type) {
    CustomLog.logBlue(Thread.currentThread().getStackTrace(), "set alarm");

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE); //ONE_TIME = "oneTime"
    intent.putExtra("c", "ayush");

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), seconds * 1000, pi);

    CustomNotification.generateNotification(1, context, "Tracking enabled");
}

And I am retrieving values in onReceive of BroadcaseReceiver: [omitted unrelated code]

@Override
public void onReceive(Context context, Intent intent) {
     Bundle extras = intent.getExtras();
     Log.e("test", extras.getString("c"); <------ ERROR
     // also tried intent.getStringExtra("c");
}
Ravers
  • 988
  • 2
  • 14
  • 45
Ayush Goyal
  • 2,079
  • 8
  • 32
  • 47

3 Answers3

4

Use the flag FLAG_UPDATE_CURRENT when calling PendingIntent.getBroadcast(). In your code:

PendingIntent pi = PendingIntent.getBroadcast(
                                 context, 0, intent, 
                                 PendingIntent.FLAG_UPDATE_CURRENT);
Italo Borssatto
  • 15,044
  • 7
  • 62
  • 88
  • I had this problem not with the getBroadcast method but with getActivity. Setting FLAG_UPDATE_CURRENT solved it for me. Maybe you can also use FLAG_CANCEL_CURRENT as suggested [here](http://stackoverflow.com/questions/18037991/pendingintent-does-not-send-intent-extras) – Michael Helwig Nov 28 '13 at 11:07
0

Try like this it will work

Intent intent = new Intent(CurrentActivity.this, AlarmManagerBroadcastReceiver.class);     
intent.putExtra("c", "ayush");

In receiver

intent.getStringExtra("c")
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
-1

Check if you are giving your onReceive(...) the correct intent as second value.

Otherwise, shouldn't the line

Bundle extras = intent.getExtras();

be more like

Bundle extras = getIntent().getExtras();

?

Jochen Birkle
  • 335
  • 4
  • 14