티스토리 뷰

728x90
반응형
안드로이드 8.0에서는 제약사항으로 인해 notification channel을 생성하여야만 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("Jungsoo", "sendNotification")

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val intent = Intent(this, MainActivity::class.java)
        intent.replaceExtras(extras)
        Log.e("Jungsoo", "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())
    }

}


반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday