简体   繁体   English

如何在Android的特定时间运行服务?

[英]How to make a Service run at a specific time in Android?

So I have this code in order to start a service at 7:32 AM every day: 因此,我有以下代码,以便每天7:32 AM启动服务:

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());

Calendar cal = new GregorianCalendar();

cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 32);


Intent start = new Intent(getActivity(), Services.class);
PendingIntent PI = PendingIntent.getService(getActivity(), 0, start, 0);
AlarmManager am = (AlarmManager)getActivity().getSystemService(getActivity().ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10*1000, PI);
getActivity().startService(start);

But it doesn't seem to work, it doesn't start the service at the specified time. 但是它似乎不起作用,它没有在指定的时间启动服务。 Can someone help me? 有人能帮我吗?

Well, first off your repeat won't work because you're setting the interval to 10 seconds. 好吧,首先重复是行不通的,因为您将间隔设置为10秒。 To make it happen daily, you want 1000*60*60*24.] 要使其每天发生,您需要1000 * 60 * 60 * 24。]

Secondly, the add to your calendar is off. 其次,添加到您的日历已关闭。 You want cur_cal.add(Calendar.DAY_OF_YEAR, 1) . 您需要cur_cal.add(Calendar.DAY_OF_YEAR, 1) This will move it to tomorrow. 这将把它移到明天。 What you're doing is basically multiplying it by 2. 您要做的基本上是将其乘以2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM