androidandroid-intentbroadcastreceiverandroid-pendingintentextras

My receiver don't receive the intent


I've this problem: i set the alarmManager with intent and pendingintent, if some conditions is satisfied, put some extras in the intent. The problem is that my receiver don't read my extras:

Set alarmManager in MainActivity:

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this , 0, i, PendingIntent.FLAG_ONE_SHOT);

       // conditions 
                    i.putExtra("type", 1);
                    i.putExtra("mealType", 2);
                    Log.d(TAG , "type: " + i.getExtras().getInt("type"));
                    Log.d(TAG , "mealtype: " + i.getExtras().getInt("mealType"));
                    calendar.set(calendar.HOUR_OF_DAY, 7);
                    am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);

And in the logcat i can see:

D/MAIN: type: 1
D/MAIN: mealtype: 2

But in my receiver:

public void onReceive(Context context, Intent intent) {

    /**
     * Receiver
     */
    Log.d(TAG, "Allarme ricevuto dal receiver");

    int type = intent.getExtras().getInt("type");
    Log.d(TAG , "type: " + type);
    Log.d(TAG , "mealtype: " + intent.getExtras().getInt("mealType"));
    Log.d(TAG , "unExisted: " + intent.getExtras().getInt("unExisted"));



    if(type == 0){
        Intent service = new Intent(context, AlarmService.class);
        service.putExtra("type", type);
        context.startService(service);
    }

    if(type == 1){
        int mealType = intent.getExtras().getInt("mealType");

        Intent service1 = new Intent(context, AlarmService.class);
        service1.putExtra("type", type);
        service1.putExtra("mealType", mealType);
        context.startService(service1);
    }
}

I see this:

D/ALARM RECEIVER: Allarme ricevuto dal receiver
D/ALARM RECEIVER: type: 0
D/ALARM RECEIVER: mealtype: 0
D/ALARM RECEIVER: unExisted: 0

I see all'key as 0 and see as a 0 "unExistest" too, i never insert this key in the intent. Why?


Solution

  • You need to set the Intent extras before creating the PendingIntent.

    Example:

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(MainActivity.this, AlarmReceiver.class);
    i.putExtra("type", 1);
    i.putExtra("mealType", 2);
    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this , 0, i, PendingIntent.FLAG_ONE_SHOT);
    calendar.set(calendar.HOUR_OF_DAY, 7);
    am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);