Oreo - Foreground service does not show foreground notification

后端 未结 3 522
醉酒成梦
醉酒成梦 2021-01-31 17:37

So far, I\'ve adjsuted my code to use ContextCompat.startForegroundService(context, intentService); to start my service. This way, it works on android < 26 and o

3条回答
  •  -上瘾入骨i
    2021-01-31 18:09

    Code in kotlin

     private fun customNotification(title: String,notificationID: Int) {
    
                    val intent = Intent(this, MainActivity::class.java)
                    val pendingIntent = PendingIntent.getActivity(this, 0 /* request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    
    
                    val builder = NotificationCompat.Builder(this, title)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setContentText("Notification description")
                            .setSmallIcon(R.drawable.ic_mark_map)
                            .setContentIntent(pendingIntent)
                            .setOnlyAlertOnce(true)
    
                    val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        val channel = NotificationChannel(title,
                                "Channel human readable title",
                                NotificationManager.IMPORTANCE_DEFAULT)
                        mNotificationManager.createNotificationChannel(channel)
                    }
    
                     val notification = builder.build()
                     startForeground(notificationID, notification)
                }
    

    Use:

     customNotification("Title",101)
    

提交回复
热议问题