NOW OR NEVER

[Android] Android Message - Notification 본문

Android

[Android] Android Message - Notification

LAURA 2023. 6. 23. 17:40
반응형

Android Message

Notification

  • 상단바를 내렸을 때 알림창에 뜨는 메세지
  • 사용자가 메세지를 확인 할 때까지 존재하는 메세지
  • 메세지 터치 시 어플리케이션 실행 가능
  • 사용자로 하여금 지속적으로 어플리케이션 사용 유도에 용이
  • 프로젝트 만든 후 emulator에서 실행 시 알림 허용 하고 테스트 해보기

addNotification 메서드

// Notification Channel을 등록하는 메서드
// 첫 번째 : 코드에서 채널을 관리하기 위한 이름
// 두 번째 : 사용자에게 노출 시킬 이름
fun addNotificationChannel(id:String, name:String){
    // 안드로이드 8.0 이상일 때만 동작하게 한다.
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        // 알림 메시지를 관리하는 객체를 추출한다.
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // id를 통해 NotificationChannel 객체를 추출한다.
        // 채널이 등록된 적이 없다면 null을 반환한다.
        val channel = notificationManager.getNotificationChannel(id)
        // 채널이 등록된 적이 없다면...
        if(channel == null){
            // 채널 객체를 생성한다.
            val newChannel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH)
            // 단말기에 LED 램프가 있다면 램프를 사용하도록 설정한다.
            newChannel.enableLights(true)
            // LED 램프의 색상을 설정한다.
            newChannel.lightColor = Color.RED
            // 진동을 사용할 것인가?
            newChannel.enableVibration(true)
            // 채널을 등록한다.
            notificationManager.createNotificationChannel(newChannel)
        }
    }
}

 

getNotification 메서드

// Notification 메시지 관리 객체를 생성하는 메서드
// Notification 채널 id를 받는다.
fun getNoficationBuilder(id:String) : NotificationCompat.Builder{
    // 안드로이드 8.0 이상이라면
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        val builder = NotificationCompat.Builder(this, id)
        return builder
    } else {
        val builder = NotificationCompat.Builder(this)
        return builder
    }
}

 

Manifest 

  • Manifest 파일 안 mainifest태그 안에 해당 코드 넣어야 함
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

 

  • import android.Manifest :  activity 파일 안에서 위 코드 작성 시 Mainifest 임포트할 패키지를 android로 택해야 한다.
Manifest.permission.POST_NOTIFICATIONS

 


etc

  • 사진 방식 중 비트맵이 메모리를 더 적게 먹는
  • 가장 점유율이 높은 자바는 java 8 버전
  • 전달된 데이터만 갱신
PendingIntent.FLAG_UPDATE_CURRENT

 

Comments