How to start Android service every 15 minutes every 15 minutes of the current time?
Hi I want to update a service running in the background every 15 minutes, specifically within 15 minutes of the current time.
Services:
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
}
// will be called asynchronously by Android
@Override
protected void onHandleIntent(Intent intent) {
updateFragmentUI();
}
private void updateFragmentUI() {
this.sendBroadcast(new Intent().setAction("UpdateChart"));
}
}
source to share
Use Alarm Manager or Task Scheduler to start the service Take a look at this link ..
How to start a service using Alarm Manager on Android?
for you I suggest using setExact instead of setRepeating. Here is the code ...
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else
am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
Remember setExact does not provide a repeating function, so every time you need to set it again from your service ... and the first time from your activity with a 10 minute delay. and in maintenance with a 15 minute delay (according to your use case).
source to share
I had the same problem, I used a recursive function from Handler
from postDelay
.
Decision:
public class UpdateService extends Service {
Handler handler = new Handler();
public UpdateService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.postDelayed(new Runnable() {
public void run() {
/*
* code will run every 15 minutes
*/
handler.postDelayed(this, 15 * 60 * 1000); //now is every 15 minutes
}
}, 0);
return START_STICKY;
}
}
source to share