编写后台服务以在特定时间致电

时间:2019-03-18 07:12:20

标签: android service

我写了一项服务,要求每2小时运行一次。但是我希望他们像这样称呼(上午8点,上午10点,下午12点等)。它不只是从开始起每隔2个小时就出现一次,如何实现?

1 个答案:

答案 0 :(得分:0)

您应该这样写:

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, YourService.class);
alarmIntent = PendingIntent.getService(context, 0, intent, 0); 

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.HOUR_OF_DAY, 12);

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, alarmIntent);