시간이 중요한 알림 표시

앱이 진행 중인 알람이나 수신 전화와 같은 특정 상황에서 긴급하게 사용자의 주의를 환기해야 할 수 있습니다. Android 9 (API 수준 28) 이하를 실행하는 기기를 타겟팅하는 앱에서는 앱이 백그라운드에 있는 동안 활동을 실행하여 이를 처리할 수 있습니다. 이 문서에서는 Android 10 (API 수준 29)~Android 13 (API 수준 33)을 실행하는 기기에서 이 동작을 실행하는 방법을 보여줍니다.

POST_NOTIFICATIONS 권한 추가

Android 13부터 AndroidManifest.xml 파일에 다음 줄을 추가합니다.

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <application ...>
        ...
    </application>
</manifest>

그런 다음 알림 채널을 만들 수 있습니다.

알림 채널 만들기

알림을 올바르게 표시하고 사용자가 앱 설정에서 알림을 관리할 수 있도록 알림 채널을 만듭니다. 알림 채널에 관한 자세한 내용은 알림 채널 만들기 및 관리를 참조하세요.

Application 클래스의 onCreate 메서드에서 알림 채널을 만듭니다.

Kotlin

class DACapp : Application() {
    override fun onCreate() {
        super.onCreate()
        val channel = NotificationChannel(
            CHANNEL_ID,
            "High priority notifications",
            NotificationManager.IMPORTANCE_HIGH
        )

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

사용자가 앱을 처음으로 실행하면 앱의 앱 정보 시스템 화면에 그림 1과 같은 내용이 표시됩니다.

앱의 앱 정보, 알림 화면을 보여주는 이미지입니다.
그림 1. 앱 시스템 설정의 App Info 화면에 있는 알림 섹션

알림 권한 관리

Android 13부터 사용자에게 알림을 표시하기 전에 알림 권한을 요청합니다.

최소 구현은 다음과 같습니다.

Kotlin

val permissionLauncher = rememberLauncherForActivityResult(
    contract = ActivityResultContracts.RequestPermission(),
    onResult = { hasNotificationPermission = it }
)
...
Button(
    onClick = {
        if (!hasNotificationPermission) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    },
) {
    Text(text = "Request permission")
}

기기에서 Android 13을 실행 중인 경우 Request permission 버튼을 탭하면 그림 2와 같은 대화상자가 트리거됩니다.

권한 요청 대화상자를 보여주는 이미지
그림 2. 알림 권한 요청의 시스템 대화상자

사용자가 권한 요청을 수락하면 앱의 앱 정보 섹션이 그림 3과 같이 표시됩니다.

알림 권한 요청이 부여된 후의 앱 정보 화면을 보여주는 이미지
그림 3. 알림 권한이 부여되었습니다.

우선순위가 높은 알림 만들기

알림을 만들 때는 구체적인 제목과 메시지를 포함합니다.

다음 예에는 알림이 포함되어 있습니다.

Kotlin

private fun showNotification() {
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    val notificationBuilder =
        NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.baseline_auto_awesome_24)
            .setContentTitle("HIGH PRIORITY")
            .setContentText("Check this dog puppy video NOW!")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)

    notificationManager.notify(666, notificationBuilder.build())
}

사용자에게 알림 표시

showNotification() 함수를 호출하면 다음과 같이 알림이 트리거됩니다.

Kotlin

Button(onClick = { showNotification() }) {
    Text(text = "Show notification")
}

이 예의 알림은 그림 4와 같습니다.

높은 우선순위 알림을 보여주는 이미지
그림 4. 우선순위가 높은 알림

진행 중인 알림

사용자에게 알림을 표시하면 사용자가 앱의 알림 또는 리마인더를 확인하거나 닫을 수 있습니다. 예를 들어 사용자는 걸려 오는 전화를 수락하거나 거부할 수 있습니다.

수신 전화와 같은 진행 중인 알림인 경우 알림을 포그라운드 서비스와 연결합니다. 다음 코드 스니펫은 포그라운드 서비스와 연결된 알림을 표시하는 방법을 보여줍니다.

Kotlin

// Provide a unique integer for the "notificationId" of each notification.
startForeground(notificationId, notification)

Java

// Provide a unique integer for the "notificationId" of each notification.
startForeground(notificationId, notification);