Send data to the alarm manager broadcast receiver

◇◆丶佛笑我妖孽 提交于 2019-12-18 19:08:31

问题


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);


来源:https://stackoverflow.com/questions/12470453/send-data-to-the-alarm-manager-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!