在特定日期和时间使用 Alarmmanager 启动服务并重复

start a service with Alarmmanager at specific date and time and Repeating

我想创建提醒应用程序

我搜索了很多地方,但找不到关于如何在每天的特定时间使用 AlarmManager 启动服务(或者如果那不可能,那么 activity)的清晰顺序解释?

我想在特定日期和时间开始服务,例如在该日期后六个月再次开始服务并继续此循环

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.YEAR, 2018);
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Intent intent = new Intent(ProfileList.this, BroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000, pintent);

我在 2018 年 2 月 12 日尝试使用此代码激活警报 9:00...这在这个日期有效,但我在例如六个月后重复时遇到问题...我该怎么做更改代码以每六个月开始服务?

注意:日期存储在数据库中,将从那里调用它们

    public class AddService extends Service
    {
        InterstitialAd mInterstitialAd;
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
           //Your Logic
            stopSelf();
            return START_NOT_STICKY;
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onDestroy() {
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.set(alarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000*60*60),
                    PendingIntent.getService(this,0,new Intent(this,AddService.class),0));
        }
    }

// Here your service will call every 1 hour, you can change time according to that

最好使用作业调度程序或 firebase 调度程序来满足您的要求

参考这个链接 https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129

https://github.com/firebase/firebase-jobdispatcher-android