🥎 알림 구성
- Notification Manager : 알림을 시스템에 발생시키는 System Service
- Notification 객체 : 알림 구성 정보를 가지는 객체
- Notification.Builder : 알림을 다양한 정보로 생성 (아이콘, 타이틀 등)
- Notification Channel : 알림의 관리 단위 (진동, 불빛, 컨텐츠타입 등)
=> Notification Channel 만든 것을 Notification Manager에 등록, 등록한 채널을 builder에 넣어서 각종 정보(아이콘, 타이틀)를 설정해서 Notification 객체 생성, 이 객체를 NotificationManage로 시스템에 등록(notifiy())
Notification Channel 만들어 Builder에 넣기
- API Level 26부터 제공되므로 버전처리를 해주어야 한다.
- 채널 생성 후 (
NotificationChannel().apply{} 로 생성) manager.createNotificationChannel(채널) 등록
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val builder: NotificationCompat.Builder
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
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)
enableVibration(true)
}
manager.createNotificationChannel(channel)
builder = NotificationCompat.Builder(this, channelId)
}else{
builder = NotificationCompat.Builder(this)
}
Notification 객체(builder) 생성
- 각종 설정들을 set 한 후, build 후 NotificationManager.notify를 통해 상태바에 등록
- notify()의 매개변수로 builder.build() 들어가는 것
builder.run{
setSmallIcon(R.drawable.small)
setWhen(System.currentTimeMillis())
setContentTitle("테스트")
setContentText("안녕하세요!!!!!!!!!")
setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.big))
}
manager.notify(11, builder.build())
🥎 알림에 대한 Action
- 일반적인 안드로이드 프로젝트 내의 touch event 사용 불가 (시스템이니까)
- Intent를 준비한 후 Notification 객체에 담아서 이벤트가 발생할 때 Intent를 실행해달라고 시스템에게 의뢰해야 한다. 이때 PendingIntent 클래스를 이용하는데, PendingIntent 클래스는 컴포넌트별로 실행을 의뢰하는 함수를 제공한다.
- 기본 형태 (
builder.addAction().build())
val actionIntent = Intent (this, OneReceiver::class.java)
val actionPendingIntent = PendingIntent.getBroadcast(this, 20, actionIntent,
PendingIntent.FLAG IMMUTABLE)
builder.addAction(
NotificationCompat.Action.Builder(
android.R.drawable.stat_notify_more,
"Action",
actionPendingIntent
).build( )
)
- 액션의 한 종류임
- RemoteInput 객체 생성하여 알림 액션 객체에 포함
- PendingIntent 객체 생성해서 사용자가 응답한 입력 추출할 수 있게 함
- 두 객체 생성됐으면
builder.AddAction()하여 pendingIntent와 remoteInput 추가
val KEY_TEXT_REPLY="key_text_reply"
val replyLabel = "답장"
val remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run{
setLabel(replyLabel)
build()
}
val replyIntent = Intent(this, MyReceiver::class.java)
val replyPendingIntent = PendingIntent.getBroadcast(
this, 30, replyIntent, PendingIntent.FLAG_MUTABLE
)
builder.addAction(
NotificationCompat.Action.Builder(
R.drawable.send,
"답장",
replyPendingIntent
).addRemoteInput(remoteInput).build()
)
https://ppeper.github.io/android/notification/