Skip to content

Instantly share code, notes, and snippets.

@dandvl
Last active December 21, 2022 00:04
Show Gist options
  • Save dandvl/505568bcd28f08689e8ac3038933ebcc to your computer and use it in GitHub Desktop.
Save dandvl/505568bcd28f08689e8ac3038933ebcc to your computer and use it in GitHub Desktop.
Foreground Services w WorkManager
implementation "androidx.work:work-runtime:2.7.1"
implementation "androidx.work:work-runtime-ktx:2.7.1"
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresStorageNotLow(true)
.build()
val workRequest = OneTimeWorkRequestBuilder<WorkerSample>()
.setConstraints(constraints)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager
.getInstance(this@MainActivity)
.enqueue(workRequest)
WorkManager.getInstance(this@MainActivity).getWorkInfoByIdLiveData(workRequest.id)
.observe(this@MainActivity) { workInfo ->
Log.d("test", "state ${workInfo?.state}")
}
}
}
class WorkerSample(val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
companion object {
private const val NOTIFICATION_CHANNEL_ID = "10"
private const val NOTIFICATION_CHANNEL_NAME = "WorkService"
}
override suspend fun doWork(): Result {
Thread.sleep(20000) //Replace with your long process
return Result.success()
}
override suspend fun getForegroundInfo(): ForegroundInfo {
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), FLAG_IMMUTABLE))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setOngoing(true)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setContentTitle(context.getString(R.string.notif_title))
.setLocalOnly(true)
.setVisibility(NotificationCompat.VISIBILITY_SECRET)
.setContentText(context.getString(R.string.notif_content))
.build()
return ForegroundInfo(6855, notification)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment