Reputation: 2375
I need to call a background service every 5 seconds, but I am facing a problem in Android 5.1 (Lollipop): it automatically considers the interval time 1 minute.
Please help me to run a background service every 5 sec.
Upvotes: 4
Views: 7484
Reputation: 180
Since the minimum interval for alarms is one minutes on Android 5.1, You can tweak your service to repeat job every 5 seconds:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy(){
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
startJob();
}
});
t.start();
return START_STICKY;
}
private void startJob(){
//do job here
//job completed. Rest for 5 second before doing another one
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//do job again
startJob();
}
}
The above code ensures one job is completed before it executes another job, hence its a cleaner approach. But if your requirement does not need to ensure completion of one job before executing another job, you can use the code below:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy(){
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(true){
startJob();
Thread.sleep(5000);
}
}
});
t.start();
return START_STICKY;
}
private void startJob(){
//do job here
}
}
And finally, you can start service by calling startService(); from your activity thread. By this, you are bypassing AlarmManager restriction. Hope it helps...
Upvotes: 6
Reputation: 1249
In Android 5.1, they appear to have set a limit, where low polling periods are rounded up to 60000ms (one minute). Repeat intervals higher than 60000ms are left alone.
For timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler
.
So if you want to achieve your goal you have to use handler to do that in android 5.1.
Refer this link https://developer.android.com/reference/android/app/AlarmManager.html#setRepeating(int, long, long, android.app.PendingIntent)
Upvotes: 4
Reputation: 1616
I don't see a problem
Either you let the service run all the time and let it wait 5 seconds b4 new tasks are being processed
Or you start every minute a thread which does every 5 seconds the tasks you want...and comes to a halt after a minute maybe just kill, initialize new one it and start it right away
Upvotes: 0