16

我在这里遗漏了一些东西,我希望有人可以帮助我。我正在使用以下方法设置警报:

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

和广播接收器使用以下内容:

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

    }

}

然而意图显然是“空的”。我看到 getStringExtra 的空值。所以数据没有被传递给广播接收器。我究竟做错了什么?我怎样才能传递数据。

非常感谢

4

1 回答 1

31

在将附加内容传递给 PendingIntent之前,您需要将附加内容添加到 Intent中:

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);
于 2012-09-19T14:43:24.757 回答