Search code examples
androidandroid-activitynotificationsalarmmanager

Don't start the notification When the activity already opened


I set an AlarmManager to open notification every 24 hours.
But every time I open the activity, the notification starts.
So how to set it not to show the notification when the activity is already opened?

This is my AlarmManager code:

AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
        Intent intent = new Intent(this, myService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
        Calendar calendar = Calendar.getInstance();
        long when = calendar.getTimeInMillis();         // notification time
        calendar.set(Calendar.HOUR_OF_DAY, 20);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 00);
        alarmManager.setRepeating(AlarmManager.RTC, when, 24*60*60*1000, pendingIntent);  //every 24 hours

Thanks ,


Solution

  • Your when variable points to the current time, hence the alarm will be fired right at execution of that part. Change when to calendar.getTimeInMillis(). Your calendar variable is set to the hour 20 of the day and repeating the day after. Here is a working copy