我在API级别24和28中测试了相同的代码。使用API 24,它每半小时显示一次通知,无论应用程序是在后台还是在前台甚至停止。但是使用API 28时,仅在应用程序处于前台时才每半小时显示一次通知。当应用在后台运行时,它会随机随机显示通知。当应用程序停止时,它永远不会显示通知。如何创建在新版本的Android中显示常规通知的应用程序?我尝试使用WorkManger和NotificationManagerCompat。 WorkManager版本是最新的2.2.0。我测试的代码很简单,我是从官方文档中获得的:
class MainActivity : AppCompatActivity() {
companion object {
const val CHANNEL_ID = "channel_id_1"
}
class MyWorker(context: Context, workerParams: WorkerParameters)
: Worker(context, workerParams ) {
override fun doWork(): Result {
var builder = NotificationCompat.Builder(applicationContext, MainActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("notificattion")
.setContentText("notification")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(applicationContext)) {
// notificationId is a unique int for each notification that you must define
notify(ThreadLocalRandom.current().nextInt(1, 1000), builder.build())
}
return Result.success()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createNotificationChannel()
val myWork = PeriodicWorkRequestBuilder<MyWorker>(30, TimeUnit.MINUTES).build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"MyUniqueWorkName",
ExistingPeriodicWorkPolicy.KEEP, myWork)
}
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, "channel mine", importance).apply {
description = "description"
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
}