1. 알림
: 앱의 UI와 별도로 사용자에게 앱과 관련된 정보를 보여주는 기능
- 알림을 터치해 해당 앱을 열 수 있음
- 문자 답하기 등의 간단한 작업은 바로 할 수 있음 (android 7.0부터)
- 보통 단말기 상단 부분에 표시되고, 앱 아이콘의 배지로도 표시 (Android 8.0부터)
2. 알림 채널
- Android 8.0 이상의 경우 알림을 만들기 전에 알림 채널을 먼저 만들어야 함
- 알림 채널은 알림을 그룹하여 알림 활성화나 방식을 변경할 수 있음
- 현재 앱이 실행 중인 안드로이드 버전을 확인, 8.0 이상인 경우만 채널 생성
private val myNotificationID = 1
private val channelID = "default"
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 8.0인지 버전을 확인함
//맞으면 NotificationChannel이라는 channel을 하나 만드는데,
// channelID가 들어가고, Notification채널의 이름, 중요도가 들어감
val channel = NotificationChannel(channelID, "default channel", NotificationManager.IMPORTANCE_DEFAULT)
//채널에 대한 description
channel.description = "description text of this channel."
// notificationManager를 통해서 시스템 서비스로부터 NOTIFICATION_SERVICE를 받아오고,
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//createNotificationChannel 에서 생성한 채널을 넣어주면 됨
notificationManager.createNotificationChannel(channel)
}
}
3. 알림 생성
1) NotificationCompat.Builder 객체에서 알림에 대한 UI 정보와 작업을 지정
- setSmallIcon() : 작은 아이콘
- setContentFile() : 제목
- setContentText() : 세부 텍스트
2) NotificationCompat.Builder.builder() 호출
- Notification 객체를 반환
3) NotificationManagerCompat.notify() 를 호출해서 시스템에 Notification 객체를 전달
private val myNotificationID = 1
private fun showNotification() {
val builder = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title")
.setContentText("notification text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
//NotificationManagerCompat에 notify하게 되면 알림이 발생함
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())
}
4. 알림 중요도
1) 채널 중요도 (Android 8.0 이상)
- NotificationChannel에서
channelID, "defaultchannel", NotificationManager.IMPORTANCE_DEFAULT
2) 알림 우선순위 (Android 7.1 이하)
- NotificationCompat.Builder(this,channelID).setPriority(NotificationCompat.PRIORITY_DEFAULT)
3) 중요도 순위
중요도 | 설명 | 중요도(Android 8.0 이상) | 우선순위 (Android 7.1 이하) |
긴급 | 알림음이 울림, 헤드업 알림 표시 | IMPORTANCE_HIGH | PRIORITY_HIGH |
높음 | 알림음이 울림 | IMPORTANCE_DEFAULT | PRIORITY_DEFAULT |
중간 | 알림음이 없음 | IMPORTANCE_LOW | PRIORITY_LOW |
낮음 | 알림음이 없음, 상태 표시줄에 표시 안 됨 | IMPORTANCE_MIN | PRIORITY_MIN |
5. 알림 확장뷰
1) 긴 텍스트 : 긴 텍스트를 추가한 확장 뷰를 알림에 넣을 수 있음 ( v 누르면 확장)
builder.setStyle(NotificationCompat.BigTextStyle()
.bigText(resources.getString(R.string.long_notification_body)))
//예시
// 알림의 기본 정보
builder.run {
//setSmallIcon(R.mipmap.ic_launcher)
//setWhen(System.currentTimeMillis())
//setContentTitle("새로운 알림입니다.")
//setContentText("알림이 잘 보이시나요.")
setStyle(
NotificationCompat.BigTextStyle()
.bigText("이것은 긴텍스트 샘플입니다. 아주 긴 텍스트를 쓸때는 여기다 하면 됩니다.이것은 긴텍스트 샘플입니다. 아주 긴 텍스트를 쓸때는 여기다 하면 됩니다.이것은 긴텍스트 샘플입니다. 아주 긴 텍스트를 쓸때는 여기다 하면 됩니다.")
)
//setLargeIcon(bitmap)
// setStyle(NotificationCompat.BigPictureStyle()
// .bigPicture(bitmap)
// .bigLargeIcon(null)) // hide largeIcon while expanding
//addAction(R.mipmap.ic_launcher, "Action", pendingIntent)
}
2) 이미지 : (v 누르면 확장) 작게 보이던 이미지가 중앙에서 크게 보임
//비트앱으로 갖고올때에는 BitmapFactory에서 접근...
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.android_hsu)
val builder = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bitmap)
.setContentTitle("Notification Title")
.setContentText("Notification body")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setStyle(NotificationCompat.BigPictureStule()
.bigPicture(bitmap)
.bigLargeIcon(null)) //hide largeIcon while expanding
3) 버튼 추가 : 알림에 버튼을 추가하고 버튼을 누르면 Intent로 Activity나 Broadcast를 시작함
- Action 버튼을 누르면 TestActivity가 시작됨
val intent = Intent(this, TestActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this,0,intent,0)
val builder = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Title")
.setContentText("Notification body")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.android_hsu, "Action", pendingIntent) // <- 이부분!
//아이콘, 이름, 눌렀을 때의 액션(인텐트 등.. 여기선 TestActivity가 실행됨)
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())
4) 프로그래스바 추가
val builder = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Progress")
.setContentText("In progress")
.setProgress(100, 0, false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())
Thread{ // 스레드로 프로그래스바 업데이트
for (i in (1..100).step(10)){
Thread.sleep(1000)
//상태를 업데이트함
builder.setProgress(100,i,false)
NotificationManagerCompat.from(this)\.notify(myNotificationID, builder.build())
}
//max = 0 이면 프로그래스바 사라짐
builder.setContentText("Completed").setProgress(0,0,false)
//같은 ID로 notify
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())
}.start()
6. 알림에 액티비티 연결
1) 알림 생성과 등록
: 알림을 터치하면 일반 액티비티인 SecondActivity가 시작, 이때 MainActivity 위에 SecondActivity가 있는 백스택을 생성
- AndroidManifest.xml 의 SecondActivity 정의 부분
<activity android:name=".SecondActivity" android:parentActivityName=".MainActivity" />
- PendingIntent 생성하고 알림 등록
//카톡에서 다른 사람과의 대화창으로 이동하듯...
// 앱 내의 다른 액티비티를 부르는 코드
val intent = Intent(this, SecondActivity::class.java)
val pendingIntent = with (TaskStackBuilder.create(this)) {
addNextIntentWithParentStack(intent)
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
}
val builder = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Title")
.setContentText("Notification body")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent) //여기에 pendingIntent를 넣어줌
.setAutoCancel(true) // auto remove this notification when user touches it
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())
2) 알림을 터치하면
(1) 알림은 사라지고, SecondActivity가 실행됨
(2) SecondActivity가 실행된 상태에서 Back이나 Up을 누르면 MainActivity가 나옴
- 사실 MainActivity가 이미 백스택에 있기 때문에 TaskStackBuilder로 백스택을 조작하지 않아도 동일하게 동작
- 백스택에 없는 다른 액티비티를 SecondActivity의 parentActivity로 하면 달라짐
'Android Studio' 카테고리의 다른 글
[Android 앱개발 심화] 데이터 저장 (1) - SharedPreferences (# 추가하기) (0) | 2024.04.30 |
---|---|
[Android 앱개발 숙련] 알림 - 예제, 권한 (# 확인...?) (0) | 2024.04.12 |
[Android 앱개발 숙련] 프래그먼트의 데이터 전달 전체코드 + 주석 (# ) (0) | 2024.04.12 |
[Android 앱개발 숙련] 프래그먼트의 데이터 전달 (# 추가하기) (0) | 2024.04.11 |
[Android 앱개발 숙련] 프래그먼트 예제 실습 (# 추가하기) (0) | 2024.04.11 |