Search code examples
androidandroid-intentalarmmanager

Passing int to BroadcastReceiver class using alarm manager


i am trying to pass two integers through the alarmmanger but whenever i pass them the toast replies null . i can't understand where the problem is .

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);

        intent.putExtra("passedHour", cal.get(Calendar.HOUR_OF_DAY));
        intent.putExtra("passedMin", cal.get(Calendar.MINUTE));

        PendingIntent alarmIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);

        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                alarmIntent);

This is the onreceive in alaramreceiver class

Toast.makeText(context, "Alarm!! " + intent.getStringExtra("passedHour") + ":" + intent.getStringExtra("passedMin"), Toast.LENGTH_LONG).show();

Solution

  • cal.get() method return int so intent is sending value as int
    You need to use intent.getIntExtra method in order to get int
    So in the onReceive use

    Toast.makeText(context, "Alarm!! " + intent.getIntExtra("passedHour") + ":" + intent.getIntExtra("passedMin"), Toast.LENGTH_LONG).show();