Problem scheduling repeating background service in Watch Face (Wear OS)

130 views Asked by At

I want to schedule a background service every 5 minutes. I'm using HandlerThread and Handler to manage the threads and JobIntentService to do the task. My code is running into the onCreate method of my watch face, which is the main app that is always displayed on my smartwatch.

The device is Wear OS based and what happens is that my code works perfectly when I'm debugging it and the smartwatch is connected to the cable. But my problem starts when I disconnect the smartwatch and the watchface goes to kind of power saving mode (= ambient mode for Wear OS developers):

Suddenly the system doesn't schedule the threads for the specified time and I start having delays. I want to run my service every specific time.

I don't know if I should use Alarm Manager instead.

This is the code for handlers:

fun manageTestingTaskSchedule() {
    val handlerThread = HandlerThread("handler-thread", Process.THREAD_PRIORITY_URGENT_AUDIO)
    handlerThread.start()
    val handler = Handler(handlerThread.looper)
    handler.postAtFrontOfQueue(RunnableTestingTask(this@MyWatchFaceSOSApp, handler))
}

I gave highest priority to threads in order to don't get delays while scheduling them.

This is code for the thread that runs the service:

class RunnableTestingTask(val watchfaceContext: Context, val handler: Handler): Runnable {
    val TAG = "RunnableTestingTask"
    override fun run() {
        val currentThread = Thread.currentThread()
        Log.i(TAG, "Thread name : " + currentThread.name + " thread priority : " + Process.getThreadPriority(Process.myTid()))

        if(WifiConnectivityChecker(watchfaceContext).isConnectedWifi()) {
            val sosMsgToGatewayIntent = Intent()
            PresenceReportService().enqueueWork(watchfaceContext, sosMsgToGatewayIntent)
        } else if(!WifiConnectivityChecker(watchfaceContext).isConnectedWifi()) {
            Log.i(TAG, "La conexion WIFI con la pasarela no se ha establecido")
        }
        handler.postDelayed(this, 300000)
    }
}
0

There are 0 answers