简体   繁体   中英

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.

How can I do above thing?

AlarmManager will help you :)

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 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.

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