如何创建一个适用于所有Android设备的时间触发通知

我试图做一个通知,经过一段时间后触发。 为了达到这个目的,我有了这个从BroadCast接收器inheritance的AlarmReceiver类,它可以运行在大约API 23的设备上。它不能在我的模拟器上运行API 27.任何线索我做错了什么?

class AlarmReceiver : BroadcastReceiver() { companion object { val PRIMARY_CHANNEL = "dj" } override fun onReceive(context: Context, intent: Intent) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationIntent = Intent(context, NotificationActivity::class.java) val stackBuilder = TaskStackBuilder.create(context) stackBuilder.addParentStack(NotificationActivity::class.java) stackBuilder.addNextIntent(notificationIntent) val pendingIntent = stackBuilder.getPendingIntent(100, PendingIntent.FLAG_UPDATE_CURRENT) if (android.os.Build.VERSION_CODES.O <= android.os.Build.VERSION.SDK_INT){ //I create the notification channel on the next line, but it doesn't seem to work val notificationChannel = NotificationChannel(PRIMARY_CHANNEL, "DailyJokes", NotificationManager.IMPORTANCE_DEFAULT) notificationChannel.lightColor = Color.GREEN notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE notificationManager.createNotificationChannel(notificationChannel) val notification = Notification.Builder(context, PRIMARY_CHANNEL) .setContentIntent(pendingIntent) .setChannelId("dj") .setContentText("KDW") .setSmallIcon(R.mipmap.ic_launcher_round) .setContentTitle("CCC") .build() notificationManager.notify(1,notification) } else { var builder = NotificationCompat.Builder(context, "dj") val sound = Uri.parse("android.resource://" + context.packageName + "/" + "raw/drumroll") builder = builder .setSmallIcon(R.mipmap.ic_launcher_round) .setColor(Color.BLUE) .setContentTitle("Content Title") .setTicker("TICKER Text") .setContentText("KDW setContentText") .setAutoCancel(true) .setContentIntent(pendingIntent) .setChannelId("dj") .setSound(sound) notificationManager.notify(1, builder!!.build()) } } } 

这是触发通知的代码,什么都不在这里?

 class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_notification) val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager val notificationIntent = Intent("android.media.action.DISPLAY_NOTIFICATION") notificationIntent.addCategory("android.intent.category.DEFAULT") val broadcast = getBroadcast(this, 100, notificationIntent, FLAG_UPDATE_CURRENT) val cal = Calendar.getInstance() cal.add(Calendar.SECOND, 5) alarmManager.set(AlarmManager.RTC_WAKEUP, cal.timeInMillis, broadcast) } } 

我的Manifest中也有一个接收器:

       

即使这样,这个bug仍然潜伏着。 我是Kotlin新手,今天开始工作一个星期。 我的快速经验为我准备好了,但我似乎无法阻止通知:/

从我的代码中可以看出,您需要将接收器注册到Manifest或上下文中。

https://developer.android.com/guide/components/broadcasts.html

你的频道是否被创造出来? 你的比较是在错误的方向 – >

android.os.Build.VERSION_CODES.O <= android.os.Build.VERSION.SDK_INT它应该是>=而不是

只有通道创建需要防范O,而不是通知创建。