-
알림(Notification)Android 2024. 4. 30. 14:58
알림 기능 오늘은 알림을 보내는 기능에 대한 코드를 포스팅 해보려고 한다.
1. 매니저, 빌더, 채널 생성
우선은 매니저와 빌더를 만들고 나서, Android 8.0 이상인 경우에는 채널을 따로 만들어야 한다.
채널을 생성할 때 아이디, 이름, 중요도 등을 넣고, 설명이나 배지를 달아준다. uri와 audio도 생성해서 setSound에 해당 변수들을 넣어준다. 그리고 생성한 채널을 매니저에 등록하면 된다.
마지막에는 빌더에다가 context와 channelId(채널을 만든 경우)을 매개변수로 넣어주고 생성한다.
fun notification() { val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager val builder: NotificationCompat.Builder if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 8.0 이상인 경우 → 채널을 만들어야 함 val channelId = "one-channel" val channelName = "My Channel One" // 채널 생성 val channel = NotificationChannel( channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT ).apply { // 채널에 대한 다양한 정보 설정 description = "My Channel One Description" setShowBadge(true) // 알림 개수 뜨는 것 val uri : Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_ALARM) .build() setSound(uri,audioAttributes) // 지금 설정된건 안드로이드 기본 사운드! 사운드 바꾸고 싶으면 mp3 다운받아서 넣어주면 됨 enableVibration(true) // 알림이 왔을 때 진동을 넣을 것인가? } // 생성한 채널을 NotificationManager에 등록 manager.createNotificationChannel(channel) builder = NotificationCompat.Builder(this,channelId) } else { // Android 8.0 이하인 경우 builder = NotificationCompat.Builder(this) } // 뒷 부분은 나중에 설명.. }
이때, setShowBadge(true) 부분은 아래와 같이 알림 갯수를 앱 화면 위쪽에 동그라미로 띄워준다.
(카카오톡을 예로 들면 이해하기가 더 쉽다)
setShowBadge(true) 2. 빌더 속성 추가 및 manager.notify 실행
이제 비트맵 이미지를 생성하거나, 알림의 액션 기능을 수행했을 때 다른 화면으로 전환하기 위해 pendingIntent 등을 설정한다.
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_cruise) val intent = Intent(this, SecondActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK // ? val pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE )
builder.run { setSmallIcon(R.drawable.ic_heart) setWhen(System.currentTimeMillis()) // 프로젝트에서 알림 발생 시간 늦추는 부분 해당 코드 건드린 것 같음 setContentTitle("setContentTitle 위치입니다.") setContentText("setContentText 위치입니다.") setStyle( NotificationCompat.BigTextStyle() .bigText("안드로이드의 알림 기능에 대한 실습을 진행 하는 중입니다. 해당 부분은 NotificationCompat.BitTextStyle().bigText에 들어가는 매개변수 부분입니다.") ) setLargeIcon(bitmap) addAction(R.drawable.ic_search, "Action", pendingIntent)// 알림을 눌렀을 때 액션 수행 } manager.notify(11, builder.build())
빌더에다가 여러 기능을 추가하고
addAction 같은 경우, Action 버튼을 눌렀을 때 pendingIntent 에서 설정한 이벤트를 발생시킬 수 있다 (대부분 intent를 통한 화면 전환인듯?)
마지막에 매니저에 notify 메소드를 통해 builder.build()를 인자로 넣어주면 실행된다.
setStyle(NotificationCompat.BigPictureStyle() .bigPicture(bitmap) .bigLargeIcon(null))
setStyle 을 아까처럼 긴 장문의 글이 나오게 할 수도 있지만, 이미지를 넣고 싶은 경우 해당 코드를 작성하면 된다.
'Android' 카테고리의 다른 글
MVC, MVVM, Repository Pattern (0) 2024.05.02 SharedPreferences (2) 2024.05.01 Multi View Type RecyclerView (0) 2024.04.29 다이얼로그 (0) 2024.04.25 프래그먼트 생명주기 (0) 2024.04.24