1

我知道要放置我可以intent.putExtra(key, value)的值并检索我们可以的值,intent.getStringExtra(key)但是在下面的代码中它的行为不符合预期。检索值时,我得到NUllPointer, printLn needs a message.

我设置值的代码:

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

我正在检索 BroadcaseReceiver 的 onReceive 中的值:[省略无关代码]

@Override
public void onReceive(Context context, Intent intent) {
     Bundle extras = intent.getExtras();
     Log.e("test", extras.getString("c"); <------ ERROR
     // also tried intent.getStringExtra("c");
}
4

3 回答 3

4

在调用PendingIntent.getBroadcast()时使用标志FLAG_UPDATE_CURRENT。在您的代码中:

PendingIntent pi = PendingIntent.getBroadcast(
                                 context, 0, intent, 
                                 PendingIntent.FLAG_UPDATE_CURRENT);
于 2013-11-23T02:20:23.697 回答
0

像这样尝试它会起作用

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

在接收器中

intent.getStringExtra("c")
于 2013-06-26T06:39:32.857 回答
-1

检查您是否将 onReceive(...) 的正确意图作为第二个值。

否则,不应该行

Bundle extras = intent.getExtras();

更像

Bundle extras = getIntent().getExtras();

?

于 2013-06-26T07:14:35.250 回答