在BroadcastReceiver的onReceive中,Intent extras为空

时间:2017-11-06 20:41:15

标签: android android-intent alarmmanager android-broadcastreceiver

我希望在BroadcastReceiver类的onReceive()方法中从Intent获取一些参数。但是只有int ALARM_COUNT = 1,虽然我放了两个args:我的Parcelable Alarm对象和test int(对于报警对象有问题的情况)。

我设置了这样的警报:

private void setCurrentAlarm(Alarm alarm) {
        long time = System.currentTimeMillis() + getClosestTimeDifference(alarm);

        mAlarmManager.set(AlarmManager.RTC_WAKEUP, time, createPendingIntent(alarm));
    }

我有如何创建PendingIntent变量:

private PendingIntent createPendingIntent(@NonNull Alarm alarm) {
        Intent intent = new Intent(mContext, AlarmBroadcastReceiver.class);

        intent.putExtra(KEY_ALARM, alarm);
        intent.putExtra("TEST", 1010120012);

        return PendingIntent.getBroadcast(mContext, alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

我的AlarmBroadcaseReceiver类中的onReceive()方法:

    @Override
    public void onReceive(Context context, Intent intent) {
           Alarm receivedAlarm = intent.getParcelableExtra(KEY_ALARM); //is always null
           int receivedInt = intent.getIntExtra("TEST", -1); //the same empty, -1
    }

正如你所看到的,Intent只包含一些ALARM_COUNT额外的,但没有我的额外内容。

怎么办?我怎么能得到它们?

2 个答案:

答案 0 :(得分:0)

您好Denis可以像String一样发送值,然后解析为int。

private PendingIntent createPendingIntent(@NonNull Alarm alarm) {
    Intent intent = new Intent(mContext, AlarmBroadcastReceiver.class);

    intent.putExtra(KEY_ALARM, alarm);
    intent.putExtra("TEST", "1010120012");

    return PendingIntent.getBroadcast(mContext, alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

@Override
public void onReceive(Context context, Intent intent) {
       Alarm receivedAlarm = intent.getParcelableExtra(KEY_ALARM); //is always null
       Bundle extras = intent.getExtras();
       String testString = (String) extras.get("TEST");
       int test = Integer.parseInt(testString)
}

您的方法onReceive

中的值为“TEST”

答案 1 :(得分:0)

使用下面示例中所示的标志对我很有帮助。

retrun PendingIntent.getBroadcast(mContext, alarm.getId(), intent, PendingIntent.FLAG_CANCEL_CURRENT)
retrun PendingIntent.getBroadcast(mContext, alarm.getId(), intent, PendingIntent.FLAG_IMMUTABLE)
retrun PendingIntent.getBroadcast(mContext, alarm.getId(), intent, PendingIntent.FLAG_ONE_SHOT)
retrun PendingIntent.getBroadcast(mContext, alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT)