在Android中,每天在特定时间设置重复警报

弓背霞明剑照霜,秋风走马出咸阳。这篇文章主要讲述在Android中,每天在特定时间设置重复警报相关的知识,希望能为你提供帮助。
我正在使用警报管理器在每天的特定时间运行警报。下面是代码

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);

【在Android中,每天在特定时间设置重复警报】我每天早上12点设置闹钟。以下是BroadCastReceiver的代码
@Override public void onReceive(Context context, Intent intent) { System.out.println("Time is 12 Am"); Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show(); }

此代码中的问题是警报被触发一旦我运行应用程序无论时间如何。任何帮助将不胜感激。谢谢
答案如果您过去设置闹钟,闹钟将立即触发。例如。它现在是10:00h,你想每天09:00设置闹钟。为了避免这种情况,您必须查看它现在的时间,如果是这种情况,则将警报移动1天...这允许您使用setRepeating方法(比setInexactRepeating更精确)
这解决了这个问题:
Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 00); calendar.set(Calendar.MINUTE, 00); if(Calendar.getInstance().after(calendar)){ // Move to tomorrow calendar.add(Calendar.DATE, 1); }//... continue like before by setting the alarm

另一答案我遇到了和你一样的问题,我无法让它发挥作用。此外,我能找到的所有例子也都设定了一个特定的日期,而不仅仅是一个时间。这应该适合你:
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

希望这可以帮助您解决问题!
另一答案试着用这个:
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, intent);

另一答案你可以使用这样的东西:
Calendar cal = Calendar.getInstance(); if(cal.getTimeInMillis() < System.currentTimeMillis()) { cal.add(Calendar.DAY_OF_YEAR, 7); }


    推荐阅读