Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Repeating Alarm Every Day at Specific time In Android

I am using Alarm manager to run alarm at specific time every day. Below is the code

 Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 00);
    calendar.set(Calendar.MINUTE, 00);

      AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, OnAlarmReceive.class);
        PendingIntent pendingIntent =PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                24*60*60*1000, pendingIntent);

I am Setting alarm at 12AM every day. And Below is the code for BroadCastReciever

@Override
   public void onReceive(Context context, Intent intent)
   {
           System.out.println("Time is 12 Am");
           Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();     
    }

Problem in this code is Alarm is Triggered As soon as i Run the Application Irrespective of time. Any help will be Appreciated. Thank You

like image 560
user3509369 Avatar asked May 20 '14 04:05

user3509369


1 Answers

I had the same issue as you and I couldn't get it to work. Plus all the examples I could find were also setting a specific date, not only just a time. This should work for you:

Intent myIntent = new Intent(ThisActivity.this , NotifyService.class);     
AlarmManager alarmManager = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(ThisActivity.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); //Repeat every 24 hours

Hope this helps you fix your problem!

like image 194
edwoollard Avatar answered Sep 28 '22 12:09

edwoollard