2017-08-25 91 views

回答

7

由于NotificationManagerCompat只是一个包装类,使生活更轻松,你可以正常创建渠道:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
    val name = getString(R.string.channel_title) 
    val description = getString(R.string.channel_description) 
    val importance = NotificationManager.IMPORTANCE_HIGH 
    val mChannel = NotificationChannel(CHANNEL_ID, name, importance) 
    mChannel.description = description 
    mChannel.enableLights(true) 
    mChannel.lightColor = Color.parseColor("#5B3C88") 
    mChannel.enableVibration(true) 
    mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400) 
    val manager = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) 
    manager.createNotificationChannel(mChannel) 
} 

然后当你发布通知使用NotificationManagerCompat,但不要忘了构造通知使用新的构造:

NotificationCompat.Builder(context, CHANNEL_ID) 
1

我通常使用这个类来管理的通知信道:

class NotificationManager(private val context: Context) { 

    companion object { 
     private val CHANNEL_ID = "YOUR_CHANNEL_ID" 
     private val CHANNEL_NAME = "Your human readable notification channel name" 
     private val CHANNEL_DESCRIPTION = "description" 
    } 

    @RequiresApi(Build.VERSION_CODES.O) 
    fun getMainNotificationId(): String { 
     return CHANNEL_ID 
    } 

    @RequiresApi(Build.VERSION_CODES.O) 
    fun createMainNotificationChannel() { 
      val id = CHANNEL_ID 
      val name = CHANNEL_NAME 
      val description = CHANNEL_DESCRIPTION 
      val importance = android.app.NotificationManager.IMPORTANCE_LOW 
      val mChannel = NotificationChannel(id, name, importance) 
      mChannel.description = description 
      mChannel.enableLights(true) 
      mChannel.lightColor = Color.RED 
      mChannel.enableVibration(true) 
      val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager 
      mNotificationManager.createNotificationChannel(mChannel) 
    } 
} 

然后你可以使用UTIL这样

fun createNotificationCompatBuilder(context: Context): NotificationCompat.Builder { 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
     return NotificationCompat.Builder(context, NotificationManager(context).mainNotificationId) 
    } else { 
     return NotificationCompat.Builder(context) 
    } 
} 

这样,您就可以与签名应用程序的任何地方使用它,就像你以前使用过,你可以很容易地改变它在未来的变化情况。