Send data to the alarm manager broadcast receiver

2020-03-01 08:11发布

问题:

I am missing something here and I hope someone can help me out. I am setting up an alarm using the following:

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent broadcast_intent = new Intent(this, AlarmBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  broadcast_intent, 0);

    broadcast_intent.putExtra("test", "ValueReceived"); //data to pass
    Date date = someVariable.getDateTime();


    long triggerAtTime = date.getTime();

    alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pendingIntent);

and the broadcast receiver using the following:

public class AlarmBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Alarm has been received "+intent.getStringExtra("test"), Toast.LENGTH_LONG).show();

    }

}

However intent s apperently "empty". I am seeing null value for the getStringExtra. So the data is not being passed to the broadcast receiver. What am I doing wrong? How can I pass data.

Thank you so much

回答1:

You need to add the extras to the Intent before you pass it to the PendingIntent:

Intent broadcast_intent = new Intent(this, AlarmBroadcastReceiver.class);
broadcast_intent.putExtra("test", "ValueReceived"); //data to pass

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  broadcast_intent, 0);