I want to create a foreground service which will run over a long period and will not become cached process in which it can be killed when memory is needed. According to the docs:
Processes that do need to be run over a long period can be created with setForeground.
So i decided to use this method to create a foreground service. Here’s what i did:
MainActivity.kt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val request = OneTimeWorkRequest.Builder(MyWorker::class.java).build()
WorkManager.getInstance(this).enqueue(request)
setContent {
Text("The app is now running")
}
}
}
MyWorker.kt
class MyWorker(context: Context, parameters: WorkerParameters):
CoroutineWorker(context, parameters) {
override suspend fun doWork(): Result {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"1",
"MAIN",
NotificationManager.IMPORTANCE_HIGH
)
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(applicationContext,"1")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("The test app is running")
.build()
val x = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ForegroundInfo(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
} else {
ForegroundInfo(1, notification)
}
setForeground(x)
return Result.success()
}
}
AndroidManifest.xml
...
<service
android:name="androidx.work.impl.foreground.SystemForegroundService"
android:foregroundServiceType="specialUse"
/>
...
After running this app nothing happens. Why? Do i start the work request correctly? Do i have to always set service name in manifest to androidx.work.impl.foreground.SystemForegroundService
? Do i have to implement my own service class when i run a foreground service this way ?