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

时间:2018-03-12 11:02:02

标签: android alarmmanager repeat

我想创建提醒应用

我已经搜索了很多地方,但是找不到每天使用AlarmManager在特定时间启动服务(或者如果那不可能是活动)的干净顺序解释?

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

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-02 / 12 9:00激活警报...这是在这个日期工作,但我有问题重复后例如六个月...如何将代码更改为每六个月开始服务一次?

注意:日期存储在数据库中并且将从那里调用

2 个答案:

答案 0 :(得分:1)

    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

答案 1 :(得分:0)

相关问题