问题
This is my code for alarm manager:
Intent intent=new Intent(getBaseContext(),AlarmReciever.class);
intent.setAction("com.example.projectx.ACTION");
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,12345, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,targetCal.getTimeInMillis(),pendingIntent);
The code works great if i select the alarm to fire off at a future hour/minute. But if I select a past hour/minute it fires up immediately as I click on "set alarm".
Example:
now it is 15:00 , i set the alarm for 15:45, alarm goes off at 15:45, everything ok
now it is 15:00 , i set the alarm for 14:30, the alarm goes off as soon as i click "set alarm"!
My time picker is always set to 24 hour mode. Could that be a problem?
Thank you!
回答1:
Of course it does... It's meant to work so.
Android recognizes that the time is past, so it will fire the alarm, even if it's late.
You can make sure that the time set for the alarm is after the current time. Just calculate this difference:
int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();
If diff is greater than 0, then add a day to your calendar (targetCal)
Now, your device's time will be earlier (instead of being later) than the next scheduled alarm time.
回答2:
I think you already found a Solution for your problem but I would like to share a concrete example with code, so that those who have the same problem and read this post, could have it a little bit easier.
AlarmManager alarmManager = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
Intent startServiceIntent = new Intent(MainActivity.this,Hintergrundservice.class);
PendingIntent startServicePendingIntent = PendingIntent.getBroadcast(MainActivity.this,0,startServiceIntent,0);
Calendar caldendar = Calendar.getInstance();
caldendar.setTimeInMillis(System.currentTimeMillis());
caldendar.set(Calendar.HOUR_OF_DAY,7);
caldendar.set(Calendar.MINUTE,1);
//long TimeDiffSL = caldendar.getTimeInMillis() - System.currentTimeMillis();
long TimeUntilTrigger;
if (System.currentTimeMillis() > caldendar.getTimeInMillis()){
TimeUntilTrigger = caldendar.getTimeInMillis() + 86400000;
Toast.makeText(getApplicationContext(),"Morgen erst",Toast.LENGTH_LONG).show();
}else{
TimeUntilTrigger = caldendar.getTimeInMillis();
Toast.makeText(getApplicationContext(),"Heute noch",Toast.LENGTH_LONG).show();
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,TimeUntilTrigger,AlarmManager.INTERVAL_DAY,startServicePendingIntent);
So the aim is to call the service Hintergrundservice.class
every day at 7:01am.
来源:https://stackoverflow.com/questions/21811882/android-alarmmanager-fires-off-for-past-time