Search code examples
androidandroid-intentbroadcastreceiveralarmmanagerandroid-pendingintent

Get extra from intent(BaseAdapter => BroadcastReceiver)


I'm working with alarm clock app. I want to add function that enables and disables alarm when you tap on particular area(all this should happen in listView with BaseAdapter). I use the code below and my BroadcastReceiver triggers at the right time. But!!! I can not get the data from intent extra: I get default extra.

Function to set an alarm:

public void setAlarm(int dayOfWeek, int hour, int minute, int position, int y) {
        // Add this day of the week line to your existing code
        Log.e("Point_1","Position " + position);
        Calendar calendar = Calendar.getInstance();

        Date previoudTime = calendar.getTime();
        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

        calendar.set(Calendar.HOUR, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent1 = new Intent(context, MyReceiver_Alarm.class);
        intent1.putExtra("Size_ABC", y);
        intent1.putExtra("key", position);
        //Log.e("Point_1", "Compare1 " + calendar.getTime());
        Log.e("Point_1", "Compare2 " + previoudTime);
        Log.e("Point_1", "Compare " + calendar.getTime().compareTo(previoudTime));
        if(calendar.getTime().compareTo(previoudTime) < 0) {

            int a = calendar.get(Calendar.WEEK_OF_MONTH);
            calendar.set(Calendar.WEEK_OF_MONTH,a + 1);
            //Log.e("Point_1", "Less " + calendar.getTime());
        }
        Long alarmTime = calendar.getTimeInMillis();

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), position , intent1, 0);
        //Also change the time to 24 hours.
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
        Log.e("Point_1", "Time is " + calendar.getTime());
    } 

And this is how I get extra

Log.e("Point_1","Position_intent " + intent.getIntExtra("key",178989800));

Guess, what number I get? Yeah,right 178989800. How to make it work right?

Thank you.


Solution

  • Instead of

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 
             position, intent1, 0);
    

    do

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(),
            position, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    

    Adding PendingIntent.FLAG_UPDATE_CURRENT ensures that your "extras" get added to the PendingIntent.