본문 바로가기
개발/Android

[Kotlin] Android Push 알림(Notification) 생성 with NotificationCompat API

by jeomn 2022. 2. 28.

1. 필요 라이브러리?

  • 최신 버전 안드로이드 스튜디오면 필요 없음
  • 아래 코드 블럭 라이브러리에 포함되어 있음
implementation 'androidx.core:core-ktx:1.7.0'
  • Android Developers 참고 中 support 계열 라이브러리가 없어서 아래의 종속성을 추가했더니 에러가 났음
implementation "com.android.support:support-compat:28.0.0"
  • "Warning Package name 'androidx.versionedparcelable' used in: AndroidManifest.xml, AndroidManifest.xml. versionedparcelable:1.1.1 manifest..."
    • support 라이브러리에서 지원하던 클래스와 메소드들이 androidx 라이브러리로 통합되면서, 중복선언으로 참조할 수 없음을 의미하는 에러
    • support 관련 라이브러리 삭제 시 정상작동

 

2. Notification Channel

  • Android 8.0 이상(API 26+)부터는 Notification Channel이 있어야함
createNotificationChannel("DEFAULT", "DEFAULT_CHANNEL", NotificationManager.IMPORTANCE_HIGH)

...

private fun createNotificationChannel(channelId : String, name : String, importance : Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(channelId, name, importance)
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

 

3. Notification

createNotification(1, "DEFAULT", "My notification", "Much longer text that can fit one line...")

...

private fun createNotification(id:Int, channelId: String, title: String, text : String){
    var builder = NotificationCompat.Builder(this, channelId)
        .setSmallIcon(R.drawable.ic_launcher_foreground)	//필수
        .setContentTitle(title)
        .setContentText(text)
        .setPriority(NotificationCompat.PRIORITY_HIGH)

	val notificationManager: NotificationManager =
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.notify(id, builder.build())
}

 

4. 버튼 연결

  • 컴포넌트에 연결하지 않고, 그냥 생성하려니 생성이 안돼서...
  • 버튼을 누르면 알림이 생성되도록 만들었습니다.

Notification 버튼을 누를 시 Notification 알림이 생성되도록

btn_noti.setOnClickListener{
    createNotification(1, "DEFAULT", "My notification", "Much longer text that can fit one line...")
}

 

5. 전체 코드

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        createNotificationChannel("DEFAULT", "DEFAULT_CHANNEL", NotificationManager.IMPORTANCE_HIGH)
        btn_noti.setOnClickListener{
            createNotification(1, "DEFAULT", "My notification", "Much longer text that can fit one line...")
        }
    }

    private fun createNotificationChannel(channelId : String, name : String, importance : Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, name, importance)
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun createNotification(id:Int, channelId: String, title: String, text : String){
        var builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_launcher_foreground)	//필수
            .setContentTitle(title)
            .setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_HIGH)

        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(id, builder.build())
    }
}

 

6. 결과

  • 성공!

Notification을 생성하는 앱, 생성된 Notification 모습

 

7. 참조

댓글