I'm trying to find a way to run a network heartbeat service on Wear OS in a reliable way. The goal would be to have a process that is sending a network request every x minutes regardless of the state of the device (screen on/off, on charger, off charger, etc). Is it possible to achieve?
My approach was to run a foreground service with a partial wake lock that is rescheduling a new Runnable with postDelayed every x minutes. But when the watch is not on the charger, it stops running as soon as the screen gets dark.
This is the basic implementation of the foreground service:
public void onCreate() {
HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
tick();
}
private void tick() {
submitDataViaNetwork();
scheduleNextTick();
}
private void scheduleNextTick() {
serviceHandler.postDelayed(new Runnable() {
public void run() {
tick();
}
}, 60*1000);
}