Migrating from Android Foreground Services to WorkManager

Viewed 135

I need some clarification regarding using WorkManager instead of Foreground service for long running and non ending service which helps to scan and advertise the BLE data even the device in standby.

I am extending the ListenableWorker and not setting any future result in startWork which helps to me run my work as long running. I need guidelines on

Is it ok to use WM like this? Will there be any performance issue? How long VM will run? Please clarify.

Sample code :

class InternalBLEWorker(private val appContext: Context, private val params:WorkerParameters) : ListenableWorker(appContext, params)

{

private var workThread: LooperThread? = null
private var bluetoothManager: BluetoothManager? = null

internal open fun createBluetoothManager(workThread: LooperThread
): BluetoothManager {
    return BluetoothManager(applicationContext, workThread)
}

companion object {

    private val running = AtomicBoolean(false)
    const val NOTIFICATION_ID = 42

}

override fun onStopped() {
    super.onStopped()
    callbackToFutureAdapter?.setCancelled()
    future.cancel(true)
   
    bluetoothManager?.apply {
        tearDown {
            workThread?.apply { post { quit() } }
        }
    }
}

override fun startWork(): ListenableFuture<Result> {
   setForegroundAsync(ForegroundInfo(NOTIFICATION_ID, InternalBLEWorkManager.getAppNotification()!!, FOREGROUND_SERVICE_TYPE_LOCATION))
    return future
}

private var callbackToFutureAdapter: CallbackToFutureAdapter.Completer<Result>? = null

private val future: ListenableFuture<Result> = CallbackToFutureAdapter.getFuture { completer ->

    callbackToFutureAdapter = completer
    val firstStart = running.compareAndSet(false, true)

    // Stop service if we are in a state where we cannot use it.
    if (!BleSupportHelper.hasBlePermission(appContext)) {
        logger.warn("Bluetooth LE permission denied, stopping BLE service")

    }else if (firstStart) {
        // Everything is OK. Set up bluetooth manager
        (LooperThread.createAndStart("Bluetooth") as LooperThread).also {
            workThread = it

            bluetoothManager = createBluetoothManager(it).apply {
                create()
                start()
            }
        }
    }
}

}

0 Answers
Related