How to start background service every 5 seconds without working in android 5.1?
Since the minimum interval for alarms is one minute on Android 5.1, you can set your service to repeat the task 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 that one job is completed before it completes another, hence a cleaner approach. But if your requirement does not need to do one job before completing another job, you can use the following code:
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
}
}
Finally, you can start the service by calling startService (); from your activity stream. This way you get around the AlarmManager limitation. Hope this helps ...
source to share
In Android 5.1 they seem to have set a limit where the low polling times are rounded to 60,000ms (one minute). Recurring intervals above 60,000 m. Remain in force.
For synchronization operations (ticks, timeouts, etc.) it is easier and more efficient to use . Handler
So, if you want to achieve your goal, you must use a handler for that in android 5.1.
Link to this link https://developer.android.com/reference/android/app/AlarmManager.html#setRepeating (int, long, long, android.app.PendingIntent)
source to share
I see no problem
Either you let the service run all the time and let it wait 5 seconds b4 new tasks are processed
Or you start every minute a thread that every 5 seconds does the tasks you want ... and stops after a minute, maybe just kills, initializes it and starts it right away.
source to share