Jungsoo Nam An android developer

Android 8.0 notification channel

안드로이드 8.0에서는 제약사항으로 인해 notification channel을 생성하여야만 notification을 표시할 수가 있다.
아래는 notification channel 생성 예제이다.

class MainActivity : AppCompatActivity() {
    private fun createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
            val channelMessage = NotificationChannel("channel_id", "channel_name", android.app.NotificationManager.IMPORTANCE_DEFAULT)
            channelMessage.description = "channel description"
            channelMessage.enableLights(true)
            channelMessage.lightColor = Color.GREEN
            channelMessage.enableVibration(true)
            channelMessage.vibrationPattern = longArrayOf(100, 200, 100, 200)
            channelMessage.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
            notificationManager.createNotificationChannel(channelMessage)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        createChannel()

        val extras = Bundle()
        extras.putString("title", "hello")
        extras.putString("message", "world")

        sendNotification(extras)
    }

    private fun sendNotification(extras: Bundle?) {
        Log.e("MainActivity", "sendNotification")

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val intent = Intent(this, MainActivity::class.java)
        intent.replaceExtras(extras)
        Log.e("MainActivity", "sendNotification intent size=$intent ${intent?.extras}")

        //PendingIntent.FLAG_UPDATE_CURRENT 추가
        //extras 전달을 위해서
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val content = extras?.getString("message")
        val title = extras?.getString("title")

        val builder = NotificationCompat.Builder(this, "channel_id")
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(content)
                .setContentTitle(title)
                .setContentIntent(pendingIntent)

        notificationManager.notify(3, builder.build())
    }
}
comments powered by Disqus