简体   繁体   中英

Intent extras are empty in onReceive of BroadcastReceiver

I want to get some arguments from Intent in onReceive() method of BroadcastReceiver class. But there's only int ALARM_COUNT = 1, although I put two args: my Parcelable Alarm object and test int (for the case when there is some problem with alarm object).

I set alarm like this:

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

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

There is how I create PendingIntent variable:

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

And onReceive() method in my AlarmBroadcaseReceiver class:

    @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
    }

As you can see Intent contains only some ALARM_COUNT extra, but there aren't my extras.

What to do? How can I get them?

Hi Denis you can send the value like a String and after do parse to 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)
}

And you will have the value of "TEST" in your method onReceive

Using flags as shown in the examples below was helpful for me.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM