简体   繁体   中英

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:

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. To make it happen daily, you want 1000*60*60*24.]

Secondly, the add to your calendar is off. You want cur_cal.add(Calendar.DAY_OF_YEAR, 1) . This will move it to tomorrow. What you're doing is basically multiplying it by 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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