Can we start foreground service from Work Manager?

Viewed 764

I am starting foreground service from the work manager doWork method.

  1. Is it ok to do so?

  2. startForegroundService should call startForeground within 5 seconds otherwise exception will happen. How to prevent this? (Note I have added startForeground in onCreate of Service)

     override fun doWork(): Result {
    
             val intent = Intent()
             intent.setClassName(App.context.packageName, "com.xyz.MySerivce")
             intent.putExtra("sync_service_initiate", true)
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                 applicationContext.startForegroundService(intent)
                 applicationContext.stopService(intent)
             } else {
                 applicationContext.startService(intent)
             }
            return Result.success()
     }
    
0 Answers
Related