vishalaestro
vishalaestro

Reputation: 125

Android Repeating Alarm not working for the next day

I need to create alarm that will trigger a local push notification every day and valid for only a particular time.

For example. Session 1 : 7 AM - 8 AM, Session 2 : 7 PM - 8 PM

From above, i need to create an alarm that will send local push notification every day at 7AM and the notification should automatically disappear at 8AM. Similarly an another alarm that will trigger a local push notification at 7 PM and remove the notification at 8 PM.

Here is the code i'm using to create the alarm and dismissing the notification when the end time reaches. I am looping the below method for 2 times to create the repeating alarm for 2 times in a day. If the current time exceeds the end time then i am pushing the notification to next day.

private void setCheckInAlarm(JSONObject checkInDetails) {
    try {
        Calendar checkInTimeCalendar = Calendar.getInstance();
        String checkInTimeUnparsed = (String) checkInDetails.get("checkInTimeIN");
        Integer checkInHour = Integer.parseInt(checkInTimeUnparsed.split(":")[0]);
        Integer checkInMinutes = Integer.parseInt(checkInTimeUnparsed.split(":")[1]);
        checkInTimeCalendar.set(Calendar.HOUR_OF_DAY, checkInHour);
        checkInTimeCalendar.set(Calendar.MINUTE, checkInMinutes);
        checkInTimeCalendar.set(Calendar.SECOND, 00);
        Calendar checkOutTimeCalendar=Calendar.getInstance();
        String checkOutTimeUnparsed=(String)checkInDetails.get("checkInTimeOUT");
        Integer checkOutHour=Integer.parseInt(checkOutTimeUnparsed.split(":")[0]);
        Integer checkOutMinutes=Integer.parseInt(checkOutTimeUnparsed.split(":")[1]);
        checkOutTimeCalendar.set(Calendar.HOUR_OF_DAY, checkOutHour);
        checkOutTimeCalendar.set(Calendar.MINUTE, checkOutMinutes);
        checkOutTimeCalendar.set(Calendar.SECOND, 0);
        Date currentTime=Calendar.getInstance().getTime();
        Date checkOutTime=checkOutTimeCalendar.getTime();
        if ( currentTime.after(checkOutTime) ) {
            checkInTimeCalendar.add(Calendar.DATE,1);
        }
            Intent intent1 = new Intent(HomeScreen.this, AlarmReceiver.class);
            intent1.putExtra("checkInId", (Integer) checkInDetails.get("checkInID"));
            intent1.putExtra("notificationTitle", (String) checkInDetails.get("checkInNotificationMessage"));
            intent1.putExtra("notificationContent", (String) checkInDetails.get("message"));
            intent1.putExtra("checkInTime", (String) checkInDetails.get("checkInTimeIN"));
            intent1.putExtra("checkOutTime", (String) checkInDetails.get("checkInTimeOUT"));
            intent1.putExtra("checkInNotify", true);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(HomeScreen.this, (Integer) checkInDetails.get("checkInID"), intent1, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager am = (AlarmManager) HomeScreen.this.getSystemService(HomeScreen.this.ALARM_SERVICE);
            am.setRepeating(AlarmManager.RTC_WAKEUP, checkInTimeCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
          //  setCheckInAlarmDismiss(checkInDetails);

    }
    catch (Exception e){
        e.printStackTrace();
        Log.d(activityName, "setCheckInAlarm: "+e);
    }
}

When the alarm is triggered, i am creating an another alarm to dismiss the notification automatically when the time is over.

Push Notification.

public class AlarmReceiver extends BroadcastReceiver
{
    public static final String activityName="AlarmReceiver";
  @Override
  public void onReceive(Context context, Intent intent) {
      Bundle bundle = intent.getExtras();
      boolean checkInNotificationDismiss=bundle.getBoolean("checkInNotify");
      if(checkInNotificationDismiss) {
          NotificationParameters notificationParameters = new NotificationParameters();
          notificationParameters.setCheckInId(bundle.getInt("checkInId"));
          notificationParameters.setMessageTitle(bundle.getString("notificationTitle"));
          notificationParameters.setMessageContent(bundle.getString("notificationContent"));
          notificationParameters.setCheckInTime(bundle.getString("checkInTime"));
          notificationParameters.setCheckOutTime(bundle.getString("checkOutTime"));

          new CheckInNotification().createNotification(notificationParameters,context,HomeScreen.class);
      }else {
          new CheckInNotification().clearAllNotications(bundle.getInt("checkInId"),context,HomeScreen.class);
      }
  }



}

Below is the class that handles notification and alarm creation to dismiss the notification.

public class CheckInNotification extends Activity {
public static final String activityName="checkNotification";
    public void createNotification(NotificationParameters notificationParameters,Context context,Class<?> cls){
        try {
            HomeScreenActions homeScreenActions = new HomeScreenActions();
            homeScreenActions.setCheckin(false);
            homeScreenActions.setRenderCheckin(true);
            homeScreenActions.setMenu(true);
            homeScreenActions.setRenderMenu(true);
            homeScreenActions.setWeather(true);
            homeScreenActions.setRenderWeather(true);
            homeScreenActions.setCheckInId(notificationParameters.getCheckInId());
            homeScreenActions.setMessageTitle(notificationParameters.getMessageTitle());
            homeScreenActions.setMessageContent(notificationParameters.getMessageContent());
          /* try {
                ConstraintLayout isHomeScreenVisible = findViewById(R.id.homeScreenLayout);
            }
            catch (NullPointerException nullPointer){
                Intent i = new Intent(CheckInNotification.this, HomeScreen.class);
                i.putExtra("actions", homeScreenActions);
                startActivity(i);
            }*/

                pushNotification(notificationParameters, homeScreenActions, context, cls);

        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    public void clearAllNotications(Integer notificationId,Context context,Class<?> cls){
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(notificationId);
    }
    private void pushNotification(NotificationParameters notificationParameters,HomeScreenActions homeScreenActions,Context context,Class<?> cls){
        try{

            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            Intent notificationIntent = new Intent(context, cls);
            Log.d(activityName, "pushNotification main: "+homeScreenActions.getCheckInId());
            Log.d(activityName, "pushNotification: "+homeScreenActions.getMessageTitle());
            Log.d(activityName, "pushNotification: "+homeScreenActions.getMessageContent());
            notificationIntent.putExtra("actions",homeScreenActions);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(cls);
            stackBuilder.addNextIntent(notificationIntent);

            PendingIntent pendingIntent = stackBuilder.getPendingIntent(
                    homeScreenActions.getCheckInId(),PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            Notification notification = builder.setContentTitle(notificationParameters.getMessageTitle())
                    .setContentText(notificationParameters.getMessageContent())
                    .setSound(alarmSound).setSmallIcon(R.mipmap.ic_launcher)
                    .setOngoing(true)
                    .setContentIntent(pendingIntent).build();

            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(homeScreenActions.getCheckInId(), notification);
            setCheckInAlarmDismiss(notificationParameters,context,cls);
    }
    catch (Exception e){
        e.printStackTrace();
        }
    }
    private void setCheckInAlarmDismiss(NotificationParameters notificationParameters,Context context,Class<?> cls) {
        try {
            Calendar calendar = Calendar.getInstance();
            String checkOut = notificationParameters.getCheckOutTime();
            Integer checkOutHour = Integer.parseInt(checkOut.split(":")[0]);
            Integer checkOutMinutes = Integer.parseInt(checkOut.split(":")[1]);
            calendar.set(Calendar.HOUR_OF_DAY, checkOutHour);
            calendar.set(Calendar.MINUTE, checkOutMinutes);
            calendar.set(Calendar.SECOND, 0);
            Intent intent1 = new Intent(context, AlarmReceiver.class);
            intent1.putExtra("checkInId", notificationParameters.getCheckInId());
            intent1.putExtra("notificationMessage", notificationParameters.getMessageTitle());
            intent1.putExtra("message", (String) notificationParameters.getMessageContent());
            intent1.putExtra("checkInNotify", false);
            intent1.putExtra("checkInTime", notificationParameters.getCheckInTime());
            intent1.putExtra("checkOutTime", notificationParameters.getCheckOutTime());
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationParameters.getCheckInId(), intent1, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
            am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        }
        catch (Exception e){
            e.printStackTrace();
            Log.d(activityName, "setCheckInAlarmDismiss: "+e);
        }
    }



}

So, the problem is when the initialize the app the alarm and the notification is created for the first time , both session1 and session2 alarm occurs but for the next day ,it does not work.

Upvotes: 1

Views: 562

Answers (1)

BEAGLE ENTERTAIN
BEAGLE ENTERTAIN

Reputation: 156

First of all, I would not only store hour, minute and second into the calendar, but also the day (and maybe the month) of the current day in case you want to do it daily.

calendar.set(Calendar.DAY_OF_MONTH, insert_current_day);
calendar.set(Calendar.MONTH, insert_current_month);
...

As soon as the alarms for both the session 1 and 2 were fired (and notification got dismissed), you then need to add one day to the calendar.

calendar.add(Calendar.DATE, 1);

before setting the AlarmService. It sets the startTime to the next day and AlarmService will fire the next day, and every day after.


Hope it's what you want and will help you.

Upvotes: 1

Related Questions