1

in alarm aplication, is there unlimited amount of alarms that the user can set ? I'm working on the option of alarm in my project, and i realized that its work only once. If i want be able to make many alarms, how should it be done, with Threads or IntentFilter, or something alse ?

public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    String title = intent.getStringExtra("Title");
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent myIntent = new Intent();
    System.out.println("Title: " + title);
    switch (title){
        case "Weight":
            myIntent = new Intent(context, WeightActivity.class);
            break;
        case "Measure":
            myIntent = new Intent(context, measurActivity.class);
            break;
        case "Pr":
            myIntent = new Intent(context, PrsActivity.class);
            break;
        case "Macros":
            myIntent = new Intent(context, DietActivity.class);
            break;
    }

    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.dumbbell)
            .setContentTitle("Tracker")
            .setContentText(title)
            .setAutoCancel(true);

    notificationManager.notify(1, builder.build());
}

}

michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63

1 Answers1

0

That's why there are requestCodes.

Note the requestCode, You just need to use different request codes for your PendingIntent while setting alarms.

public setMyAlarm(int requestCode){

AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() +
        60 * 1000, alarmIntent);
}

Since the type of requestCode is int, so that should be more than enough to set much amount of alarms.

Also for cancelling the alarm you will have to mention the Pending intent with the same requestCode, you used to set alarm.

Please don't misunderstand it with your Notification's PendingIntent.

Man
  • 2,720
  • 2
  • 13
  • 21
  • Thanks. Maybe you also can help with how its should be don if im want the alarm to repeat any given day ? – Tal Brodkin Nov 05 '17 at 15:12
  • To set repeating alarm you can use `alarmMgr.setRepeating()`, And to set it at specific day you may use Calendar and set day using `Calendar.DAY_OF_WEEK` and pass it as milliseconds. – Man Nov 05 '17 at 16:47