320x100
특정 버튼을 누름으로써
알림을 생성하는 작업을 하고자 한다
알림의 경우 매우 기초적인 방법을 사용하였고,
지금은 특정 버튼 이지만
사용처에 따라 특정 이벤트, 상황에 따라
적용하면 될 것 같다
코드 1 : MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var notificationManager: NotificationManager
private lateinit var bNotiCall: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 알림 매니저
notificationManager = getSystemService(
Context.NOTIFICATION_SERVICE) as NotificationManager
// 특정 버튼
bNotiCall = findViewById(R.id.b_noti_call)
// 클릭 이벤트
bNotiCall.setOnClickListener { notificationShow() }
}
private fun notificationShow() {
createNotificationChannel()
// 알림 생성
val builder = NotificationCompat.Builder(this, "test_noti_channel")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Notification Title")
.setContentText("Notification Body ~~")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
// 알림 호출
notificationManager.notify(0, builder.build())
}
// 채널 생성 - 오레오 버전 이상 부터
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
"test_noti_channel",
"Stand up notification",
NotificationManager.IMPORTANCE_HIGH
)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.description = "Notification Test"
notificationManager.createNotificationChannel(
notificationChannel)
}
}
}
코드 2 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/b_noti_call"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="알림 호출" />
</LinearLayout>
320x100
'Android > Kotlin' 카테고리의 다른 글
[Android][Kotlin] Thread 에러 처리 및 UI 변경 활용 예제 (0) | 2022.10.20 |
---|---|
[Android][Kotlin] 알람매니저(AlarmManager)를 이용한 알림(Notification) 호출하기 (0) | 2022.10.14 |
[Android][Kotlin] 캘린더(CalendarView) 생성, 오늘 날짜, 클릭 이벤트 (0) | 2022.10.12 |
[Android][Kotlin] Thread 상속 받고 Thread 일시정지 (0) | 2022.10.07 |
[Android][Kotlin] Dialog 커스텀 및 스타일 수정 (0) | 2022.10.05 |