Android WorkManager-CoroutineWorker后台运行发送Notification通知到前台通知栏,kotlin
Posted zhangphil
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android WorkManager-CoroutineWorker后台运行发送Notification通知到前台通知栏,kotlin相关的知识,希望对你有一定的参考价值。
android WorkManager-CoroutineWorker后台运行发送Notification通知到前台通知栏,kotlin(2)
package com.example.myapplication
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_MIN
import androidx.work.*
val TAG = "zhangphil"
fun notification(context: Context, s: String): Notification
var channelId = createNotificationChannel(context, "com.fly", "Foreground_Service") ?: ""
return NotificationCompat.Builder(context, channelId)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_notification_overlay)
.setContentTitle("我的标题")
.setContentText(s)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
private fun createNotificationChannel(
context: Context,
channelId: String,
channelName: String
): String?
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
channel.lightColor = Color.BLUE
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service?.createNotificationChannel(channel)
return channelId
class ForegroundWorker(private val context: Context, parameters: WorkerParameters) :
CoroutineWorker(context, parameters)
override suspend fun getForegroundInfo(): ForegroundInfo
return ForegroundInfo(1, notification(context, "zhangphil"))
override suspend fun doWork(): Result
setForegroundAsync(getForegroundInfo())
repeat(1000)
Thread.sleep(1000)
Log.d(TAG, "do work " + it)
return Result.success()
class MainActivity : AppCompatActivity()
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
val request = OneTimeWorkRequestBuilder<ForegroundWorker>()
.setExpedited(OutOfQuotaPolicy.DROP_WORK_REQUEST)
.build()
WorkManager.getInstance(applicationContext)
.enqueue(request)
override fun onStart()
super.onStart()
println("前台")
override fun onStop()
super.onStop()
println("后台")
配置权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
记得在手机的应用列表设置运行这个app允许通知。
以上是关于Android WorkManager-CoroutineWorker后台运行发送Notification通知到前台通知栏,kotlin的主要内容,如果未能解决你的问题,请参考以下文章
Android 逆向Android 权限 ( Android 逆向中使用的 android.permission 权限 | Android 系统中的 Linux 用户权限 )