Android 使用 Alarmmanager 在特定时间启动服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3052149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Alarmmanager to start a service at specific time
提问by JaVadid
I have searched a lot of places but couldnt find a clean sequential explanation of how to start a service (or if thats not possible then an activity) at a specific time daily using the AlarmManager??
我已经搜索了很多地方,但找不到关于如何在每天的特定时间使用 AlarmManager 启动服务(或者如果那不可能则是活动)的清晰顺序解释?
I want to register several such alarms and triggering them should result in a service to be started. I'll be having a small piece of code in the service which can then execute and i can finish the service for good....
我想注册几个这样的警报,触发它们应该会导致服务启动。我将在服务中有一小段代码,然后可以执行,我可以永久完成服务......
Calendar cal = Calendar.getInstance();
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Date date = new Date(cur_cal.get(Calendar.YEAR), cur_cal.get(Calendar.MONTH), cur_cal.get(Calendar.DATE), 16, 45);
cal.setTime(date);
Intent intent = new Intent(ProfileList.this, ActivateOnTime.class);
intent.putExtra("profile_id", 2);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
System.out.println("The alarm set!!");
i tried this code to activate the alarm at 4.45... but its not firing the service... do i have to keep the process running?? M i doing anything wrong???
我尝试使用此代码在 4.45 激活警报......但它没有启动服务......我必须保持进程运行吗??我做错了什么???
One more thing, my service gets perfectly executed in case i use the following code:
还有一件事,如果我使用以下代码,我的服务将得到完美执行:
long firstTime = SystemClock.elapsedRealtime();
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000,pintent);
回答by JaVadid
HI friends, After a lot of researching and with reference from "Pentium10"'s question on the same topic i managed to get it working. Though i still cant understand why the "date" concept and the Calendar(non GregorianCalendar) object which i have mentioned in the question are not working correctly.
嗨朋友们,经过大量研究并参考“Pentium10”关于同一主题的问题,我设法让它工作。虽然我仍然无法理解为什么我在问题中提到的“日期”概念和日历(非公历日历)对象无法正常工作。
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.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this, IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
回答by M P Mathugama
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReciever.class);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
Intent intent0 = new Intent(this, OldEntryRemover.class);
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, 19);
timeOff9.set(Calendar.MINUTE, 20);
timeOff9.set(Calendar.SECOND, 0);
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, timeOff0.getTimeInMillis(), pendingIntent0);
Then in your AlarmReciever class which is a broadcastReciever, under onRecieve method put your logic. This will take care of what ever the logic you want to handle when the time comes to 7.20 pm.
然后在你的 AlarmReciever 类中,这是一个广播接收器,在 onRecieve 方法下放置你的逻辑。当时间到晚上 7.20 时,这将处理您想要处理的逻辑。
If you need to set multiple alarms, create another Calendar instance & set time values appropriately. You also need to create another instance for pendingIntent otherwise timers will overlap. Then set it to same alarmManager with new timer & pendingIntent.
如果您需要设置多个闹钟,请创建另一个日历实例并适当设置时间值。您还需要为 pendingIntent 创建另一个实例,否则计时器将重叠。然后使用新的计时器和pendingIntent 将其设置为相同的alarmManager。
回答by user2481102
You can read document from https://developer.android.com/training/scheduling/alarms.html
您可以从https://developer.android.com/training/scheduling/alarms.html阅读文档
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
// 设置闹钟在早上 8 点 30 分开始
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case, // 20 minutes.
// setRepeating() 可让您指定精确的自定义间隔——在本例中为 // 20 分钟。
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
回答by Prasanth.NVS
The following code should work fine and it starts the service @ 7:40 PM every day. Also, if device shuts down then all your alarms get cancelled.
下面的代码应该可以正常工作,并且每天晚上 7:40 开始服务。此外,如果设备关闭,那么您的所有警报都会被取消。
Make sure to set up all the alarms after BOOT is completed.
确保在 BOOT 完成后设置所有警报。
Intent slIntent = new Intent(this, x.class);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
PendingIntent slPendingIntent = PendingIntent.getService(this, 1, slIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, slPendingIntent);
回答by hassan karimi
codes above didn't work and below code worked for me.
上面的代码不起作用,下面的代码对我有用。
month decreases 1. and hours 0-11.
月减少 1. 和小时 0-11。
int day = ff.getGregorianDay() ;
int month = ff.getGregorianMonth() ;
int year = ff.getGregorianYear();
int hour = TimePicker1.getCurrentHour();
int minute = TimePicker1.getCurrentMinute();
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeInMillis(System.currentTimeMillis() );
cal_alarm.set(Calendar.YEAR, year);
cal_alarm.set(Calendar.MONTH, month-1);
cal_alarm.set(Calendar.DAY_OF_MONTH, day);
cal_alarm.set(Calendar.AM_PM, Calendar.AM );
cal_alarm.set(Calendar.HOUR, hour);
if( hour >= 12){
cal_alarm.set(Calendar.AM_PM, Calendar.PM );
cal_alarm.set(Calendar.HOUR, hour-12);
}
cal_alarm.set(Calendar.MINUTE, minute );
cal_alarm.set(Calendar.SECOND, 0 );
Intent myIntent = new Intent(YadavariNewActivity.this, Alarm_Sag.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(YadavariNewActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set( AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
回答by sharma_kunal
I tried a lot To Start Service on Time So I Have one solution like
我尝试了很多按时启动服务所以我有一个解决方案,例如
Calculate the differencebetween current time and selected timefrom date picker "Return Long timeMileSec= Milliseconds" Difference
after this create a handler inside it and Sleep if "Milliseconds" seconds
new Handler().postDelayed(new Runnable() { @Override public void run() { CreateService(); getActivity().startService(intentServiceObj); } }, timeMileSec); // Below is the service Methods. private void CreateService() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.add(Calendar.DAY_OF_YEAR, year); cal.set(Calendar.HOUR_OF_DAY, hourScreen); cal.set(Calendar.MINUTE, minuteScreen); // cal.setTimeInMillis(timeselectedmillisecond); Intent intent = new Intent(getActivity(), ServiceDailyLocationUpdate.class); pintent = PendingIntent.getService(getActivity(), 0, intent, 0); alarm = (AlarmManager) getActivity().getSystemService( Context.ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.HOUR, 86000 * 1000, pintent); } // Return Differnce between two date private long calculateDateDiffSecond(String firstDate, String secondDate) { long numberOfDays = 0; String dateStart = firstDate; String dateStop = secondDate; Date d1 = null; Date d2 = null; try { d1 = sdfTime.parse(dateStart); d2 = sdfTime.parse(dateStop); // in milliseconds long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print(diffDays + " days, "); System.out.print("Hours::" + diffHours + " hours, "); System.out.print("HoursMinute::" + diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds."); numberOfDays = diffDays; numberOfDays = diff; } catch (Exception e) { e.printStackTrace(); } return numberOfDays; }
计算差异之间的当前时间和选择的时间从日期选择器“返回龙timeMileSec=毫秒”差异
在此之后在其中创建一个处理程序并在“毫秒”秒时睡眠
new Handler().postDelayed(new Runnable() { @Override public void run() { CreateService(); getActivity().startService(intentServiceObj); } }, timeMileSec); // Below is the service Methods. private void CreateService() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.add(Calendar.DAY_OF_YEAR, year); cal.set(Calendar.HOUR_OF_DAY, hourScreen); cal.set(Calendar.MINUTE, minuteScreen); // cal.setTimeInMillis(timeselectedmillisecond); Intent intent = new Intent(getActivity(), ServiceDailyLocationUpdate.class); pintent = PendingIntent.getService(getActivity(), 0, intent, 0); alarm = (AlarmManager) getActivity().getSystemService( Context.ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.HOUR, 86000 * 1000, pintent); } // Return Differnce between two date private long calculateDateDiffSecond(String firstDate, String secondDate) { long numberOfDays = 0; String dateStart = firstDate; String dateStop = secondDate; Date d1 = null; Date d2 = null; try { d1 = sdfTime.parse(dateStart); d2 = sdfTime.parse(dateStop); // in milliseconds long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print(diffDays + " days, "); System.out.print("Hours::" + diffHours + " hours, "); System.out.print("HoursMinute::" + diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds."); numberOfDays = diffDays; numberOfDays = diff; } catch (Exception e) { e.printStackTrace(); } return numberOfDays; }