Search code examples
javaandroidandroid-studiobroadcastreceiver

BroadcastReceiver received more than once


I am getting a problem with my reminder APP.

  • When I add first reminder broadcast is received once for second time broadcast is received twice for third time it is received thrice.

I tried many different solutions on StackOverfolow but none of them are working

Kindly help me out with detailed answer.

Link to Project . code is given below:

Function to set Reminder:

public void startAlarm(Calendar c) {
    
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlertReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, number, intent, PendingIntent.FLAG_ONE_SHOT);
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}

Class receiving Broadcast:

public class AlertReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, intent.getAction(), Toast.LENGTH_LONG).show();

        MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_NOTIFICATION_URI);
        mediaPlayer.start();
    }
}

Solution

  • I see that you are setting the alarm inside Adapters onBindViewHolder. This is not the right place to setting alarm. Because when you call notifyDataSetChanged it will call onBindViewHolder again and it will set same alarm over and over.