简体   繁体   English

在特定时间在Android中致电服务

[英]Call service at specific time in android

I have service run in background. 我的服务在后台运行。
I want to call this service at specific interval. 我想在特定时间间隔调用此服务。
if user provide values 10, 20, 30 than service should call after 10 min,20 min and 30 min receptively. 如果用户提供的值是10、20、30,则服务应分别在10分钟,20分钟和30分钟后致电。

How can I do above thing? 我该如何做呢?

AlarmManager will help you :) AlarmManager将为您提供帮助:)

It allows you to set up a schedule to launch your application's components during the specified time range 它允许您设置时间表以在指定的时间范围内启动应用程序的组件

Update 更新

To instantiate an AlarmManager that will go into play at the specific period after it's instantiating, configure it with setRepeating() method and PERIOD parameter added to SystemClock.elapsedRealime() : 要实例化将在实例化后的特定时间段内运行的AlarmManager ,请使用setRepeating()方法和添加到SystemClock.elapsedRealime() PERIOD参数对其进行配置:

AlarmManager mgr = (AlarmManager)getSystemService(ALARM_SERVICE);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
                     SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi); // Here PERIOD is a value specified by you as PendingIntent object

You can set an Alarm to have an Intent fired at specific interval. 您可以将警报设置为以特定间隔触发意图。 You can also set an inexact alarm if it is not critical that the alarm runs at the precise time. 如果警报在精确的时间运行并不重要,则还可以设置不精确的警报。

Calendar startTime = Calendar.getInstance();
        startTime.set(Calendar.HOUR_OF_DAY, 10);
        startTime.set(Calendar.MINUTE, 20);
        startTime.set(Calendar.SECOND, 25);

        Intent dailyQuotes = new Intent(getActivity(), DailyQuotesService.class);
        AlarmManager am = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(getActivity(), 0, dailyQuotes, 0);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, startTime.getTimeInMillis(), 30000, pi);

here is my code and it call my service exactly on specified time. 这是我的代码,它恰好在指定的时间调用我的服务。 and then is repeated every 30 secs. 然后每30秒重复一次。

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

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