Skip to content

Instantly share code, notes, and snippets.

@sum20156
Last active December 3, 2022 05:44
Show Gist options
  • Save sum20156/36118191d4b7afe73170909d3f06b6f9 to your computer and use it in GitHub Desktop.
Save sum20156/36118191d4b7afe73170909d3f06b6f9 to your computer and use it in GitHub Desktop.
Workmanager with foreground service
package com.sumanmsoft.dashboard
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.work.*
import com.google.common.util.concurrent.ListenableFuture
import kotlinx.coroutines.delay
class TestService(val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
delay(10000) //simulating long work
return Result.success()
}
override suspend fun getForegroundInfo(): ForegroundInfo {
return createForegroundInfo()
}
private fun createForegroundInfo(): ForegroundInfo {
val id = "213"
val title ="title"
val cancel = "cancel"
// This PendingIntent can be used to cancel the worker
val intent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(getId())
// Create a Notification channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel()
}
val notification = NotificationCompat.Builder(applicationContext, id)
.setContentTitle(title)
.setTicker(title)
.setContentText("test")
.setSmallIcon(R.drawable.ic_telegram)
.setOngoing(true)
// Add the cancel action to the notification which can
// be used to cancel the worker
.addAction(android.R.drawable.ic_delete, cancel, intent)
.build()
return ForegroundInfo(100, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() {
val mChannel = NotificationChannel("CHANNEL_ID", "nam", NotificationManager.IMPORTANCE_DEFAULT)
mChannel.description = "descriptionText"
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
// Create a Notification channel
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment