Search code examples
androidbroadcastreceiveralarmmanagerandroid-broadcastreceiver

How to set up multiple BroadcastReceivers in an app


I'm creating an app that lists upcoming movies, the user sets a reminder for any movie he wants to be reminded about when its release is approaching (using DatePicker he chooses the date when the notification will pop up). So you guessed it each movie will be capable to ho have a notification. I'm guessing to do this, I need to put the movie's name and id in a SharedPreference when the user sets the reminder like so;

public void setAlarm(View view){ 

     Intent alertIntent = new Intent(this, AlertReceiver.class);

     SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
     SharedPreferences.Editor editor = settings.edit();
     editor.putString("name", name);
     editor.putInt("id", mainId);
     editor.commit();

     AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // set() schedules an alarm to trigger
    // FLAG_UPDATE_CURRENT : Update the Intent if active
    alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
            PendingIntent.getBroadcast(this, 1, alertIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT));
}

Then on the OnRecieve() method I get the SharedPreference and use the name and id to build a message

public void onReceive(Context context, Intent intent) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    String name = settings.getString("name", "");
    int id = settings.getInt("id", 0);
    createNotification(context, "" ,  name + " Coming soon" , name, id);
}


public void createNotification(Context context, String msg, String msgText, String msgAlert, int id){

    // Define an Intent and an action to perform with it by another application
    PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

    // Builds a notification
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setContentTitle(msg)
            .setContentText(msgText)
            .setTicker(msgAlert)
            .setSmallIcon(R.mipmap.ic_launcher);

    //the intent when the notification is clicked on
    mBuilder.setContentIntent(notificIntent); //goes to MainActivity

    //how the user will be notified
    mBuilder.setDefaults(NotificationCompat.DEFAULT_LIGHTS);

    //stop notification when it's clicked on
    mBuilder.setAutoCancel(true);

    //now to notify the user with NotificationManager
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(id, mBuilder.build());
}

OnReceive works great, but it seems I could only create one reminder at a time, like SharedPreference overwrite the old with the new, i think? Do I need to declare a new SharedPreference for each movie I setAlarm() to? Then the BroadcastReceiver's OnReceive method will get the values out of the SharedPreference?


Solution

  • SharedPreference is not required in your case, you can directly put data to intent and get that data from intent in onReceive method.

    If you want to set multiple alarms (repeating or single), then you just need to create their PendingIntents with different requestCode. If requestCode is the same, then the new alarm will overwrite the old one. For this you can use System.currentTimeMillis();

    public void setAlarm(View view){ 
    
         Intent alertIntent = new Intent(this, AlertReceiver.class);
    
         alertIntent.putExtra("name", name);
         alertIntent.putExtra("id", mainId);
    
    
         AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
        // set() schedules an alarm to trigger
        // FLAG_UPDATE_CURRENT : Update the Intent if active
        alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
                PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), alertIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT));
    }
    

    onReceive method get data from intent

    public void onReceive(Context context, Intent intent) {
    
    
    if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            //reset your alarm here save your alarms in database or shared    //preferences so that you can reset here
        }else{
            String name = intent.getStringExtra("name", "");
            int id = intent.getIntExtra("id", 0);
            createNotification(context, "" ,  name + " Coming soon" , name, id);
    }
        }