Reputation: 5696
I am writing a data logger app and I need to make an http request every 5 minutes exactly. The user is aware of the battery drain and that's ok for me. I am using a foreground service with the appropriate notification for that and I have a handler thread to witch I post runnable tasks every 5 minutes. It seems that when the phone enter DOZE MODE the thread is suspended and no runnables are executed. Is that normal behaviour or I am missing something? Any help on how to do that will be appreciated.
Service code that starts the thread:
private void startTheForegroundService() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainService.this);
builder.setPriority(Notification.PRIORITY_HIGH);
startForeground(1000, builder.build());
httpThread = new HttpThread("Ping Thread", Thread.NORM_PRIORITY);
httpThread.start();
httpThread.loop();
}
Thread code:
public class HttpThread extends HandlerThread {
public Handler mHandler;
public HttpThread(String name, int priority) {
super(name, priority);
}
public synchronized void waitUntilReady() {
mHandler = new Handler(getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
}
public void loop() {
waitUntilReady();
mHandler.post(new Runnable(){
@Override
public void run() {
//code for the http request.
}
});
}
}
Upvotes: 3
Views: 2271
Reputation: 1006724
Is that normal behaviour
Yes, for the Doze mode in Android 6.0, which triggers when the app has been stationary for an hour or so. The M Developer Preview extends Doze mode, such that it also partially triggers even when the device is moving, though I think your scenario would continue to work in that case.
The user is aware of the battery drain
The user can add you to the battery optimization whitelist (Settings > Apps > (gear icon) > Battery Optimization).
Upvotes: 1