NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
.setContentTitle("지오펜싱 서비스")
.setContentText("지오펜싱이 활성화되었습니다.")
.setSmallIcon(R.drawable.baseline_alarm_on_24)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true) // 알림이 사용자가 밀어서 제거되지 않도록 설정
.addAction(
android.R.drawable.ic_delete, // STOP 버튼의 아이콘
"Stop", // STOP 버튼의 텍스트
stopPendingIntent // 버튼 클릭 시 동작
)
.build()
원래라면 위와 같이 setOngoing()의 값을 true로 설정해서 notification을 만들면 알림을 닫을 수 없었다.
하지만 안드로이드 14 버전 이후에 아래의 사진처럼 닫을 수 있도록 변경되었다.
포그라운드 서비스로 지오펜싱하고 있는 것을 사용자에게 알려야 했기 때문에 지오펜싱을 종료하기 전에는 알림으로 사용자에게 계속 알려야 했다.
방법을 찾다가 setDeleteIntent()를 발견했다.
사용자가 알림을 명시적으로 삭제할 때 실행되는 PendingIntent를 설정하는 메서드이다.
val dismissedIntent = Intent("DISMISSED_ACTION")
dismissedIntent.setPackage(packageName) // This is required on Android 14
val dismissedPendingIntent = PendingIntent.getBroadcast(
this,
1,
dismissedIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
return NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
.setContentTitle("지오펜싱 서비스")
.setContentText("지오펜싱이 활성화되었습니다.")
.setSmallIcon(R.drawable.baseline_alarm_on_24)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setDeleteIntent(dismissedPendingIntent)
.addAction(
android.R.drawable.ic_delete, // STOP 버튼의 아이콘
"Stop", // STOP 버튼의 텍스트
stopPendingIntent // 버튼 클릭 시 동작
)
.build()
알림을 생성할 때 사용자가 알림을 해제할 때 실행되는 PendingIntent를 setDeleteIntent(PendingIntent)를 사용하여 설정한다.
private val onNotificationDismissedReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification = createNotification()
notificationManager.notify(1, notification)
}
}
알림이 해제될 때 다시 알림을 표시하는 BroadcastReceiver를 만든다.
override fun onCreate() {
super.onCreate()
Log.i("geofence", "서비스 시작")
...
registerReceiver(
onNotificationDismissedReceiver,
IntentFilter("DISMISSED_ACTION"),
RECEIVER_NOT_EXPORTED // This is required on Android 14
)
}
override fun onDestroy() {
...
unregisterReceiver(onNotificationDismissedReceiver)
...
}
receiver를 등록해주고 해제도 잊지말고 해주자.
그러면 "stop"버튼을 누르지 않는 이상 슬라이드로 알림을 없애도 다시 생겨나는 것을 확인할 수 있다.