메인 콘텐츠로 건너뛰기
OneSignal의 Android 라이브 알림을 사용하면 단일 알림에 실시간 업데이트를 보낼 수 있어 혼잡함을 줄이고 참여도를 향상시킬 수 있습니다. 이러한 알림은 지속적으로 유지되며 콘텐츠를 동적으로 업데이트합니다. 스포츠 점수, 다운로드 진행 상황 또는 이벤트 추적에 이상적입니다. 라이브 알림을 받으려면 Android 사용자는 푸시 알림을 활성화해야 합니다.

요구 사항

  • 앱은 최신 버전의 OneSignal SDK를 사용해야 합니다.
  • Android 사용자는 푸시 알림 권한을 활성화해야 합니다.

라이브 알림 vs. 표준 푸시

매번 새 알림을 보내는 일반 푸시 알림과 달리 라이브 알림은 시간이 지남에 따라 업데이트되는 단일 알림을 사용합니다. 업데이트는 동일한 collapse_id를 사용하여 Create Message API를 통해 전송됩니다.

구성

1. 알림 서비스 확장 구현

INotificationServiceExtension을 구현하는 NotificationServiceExtension 클래스를 만듭니다. 이 클래스는 들어오는 알림을 가로채서 수정하거나 재정의할 수 있습니다.
자세한 내용은 Android 알림 서비스 확장을 참조하세요.
NotificationServiceExtention.kt
package com.onesignal.sample.android

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import com.onesignal.notifications.INotificationReceivedEvent
import com.onesignal.notifications.INotificationServiceExtension
import org.json.JSONObject
import java.util.logging.Logger

class NotificationServiceExtension : INotificationServiceExtension {
  override fun onNotificationReceived(event: INotificationReceivedEvent) {
        val context = event.context
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
            ?: run {
                logger.warning("NotificationManager not available.")
                return
            }

        notificationManager.let {
            if (!notificationChannelsCreated) {
                createNotificationChannels(notificationManager)
            }
        }

        // Use `additional_data`to submit the Live Notification payload.
    		val additionalData = event.notification.additionalData
        val liveNotificationPayload = additionalData?.optJSONObject("live_notification")
        if (liveNotificationPayload == null) {
            logger.info("No live notification payload found. Showing original notification.")
            return
        }

        event.preventDefault()
        handleLiveNotification(event, liveNotificationPayload, notificationManager, context)
    }
}

2. Android Manifest에 확장 추가

  <meta-data android:name="com.onesignal.NotificationServiceExtension"
              android:value="com.onesignal.sample.android.NotificationServiceExtension" />

3. 라이브 알림 유형 만들기

라이브 알림 유형은 어떤 라이브 알림을 시작할지 나타냅니다.

키 정의

라이브 알림은 key로 참조되며, 이는 업데이트가 라우팅되는 방법을 결정합니다.
NotificationServiceExtention.kt
private const val PROGRESS_LIVE_NOTIFICATION = "progress"

알림 채널 만들기

채널은 알림의 동작(소리, 진동, 모양)을 정의합니다. 라이브 알림 유형에 대한 채널을 만들어야 합니다. 권장 사항:
  • 진행 알림에는 낮은 중요도 사용
  • 배지 비활성화
  • 소리 및 진동을 최소화
자세한 내용은 Android 알림 채널 카테고리를 참조하세요.

라이브 알림 디자인

라이브 알림을 디자인할 때 각 업데이트 유형에 대한 알림 디자인을 만들 수 있는 유연성이 있습니다. 만드는 각 디자인에는 특정 유형이 할당되어야 하므로 라이브 알림의 다양한 표현이 가능합니다.
NotificationServiceExtention.kt
private fun updateProgressNotification(
        liveNotificationUpdates: JSONObject,
        context: Context,
        notificationManager: NotificationManager
    ) {
        val currentProgress = liveNotificationUpdates.optInt("current_progress", 0)

        val builder = NotificationCompat.Builder(context, PROGRESS_CHANNEL_ID)
            .setContentTitle("Progress Live Notifications")
            .setContentText("It's working...")
            .setSmallIcon(android.R.drawable.ic_media_play)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, android.R.drawable.ic_dialog_info))
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .setProgress(100, currentProgress, false)
            .setAutoCancel(false) // Prevent auto-dismissal of notification until you set the end event

        notificationManager.notify(keyMap[PROGRESS_LIVE_NOTIFICATION]!!, builder.build())
        logger.info("Updated progress notification with progress: $currentProgress")
    }
디자인 고려 사항:
  • 작은 아이콘 및 강조 색상
  • 큰 아이콘
  • 큰 그림
  • 작업 버튼
고급 디자인 옵션은 Android 사용자 지정 알림 레이아웃을 참조하세요.

4. 라이브 알림 페이로드 추출

라이브 알림은 additional_data 필드를 사용하여 구조화된 콘텐츠를 전달합니다.
NotificationServiceExtention.kt
val additionalData = event.notification.additionalData
val liveNotificationPayload = additionalData?.optJSONObject("live_notification")

라이브 알림 스키마

속성필수설명
key올바른 알림 UI를 로드하는 데 사용됩니다.
event라이브 알림에서 수행할 작업입니다.
event_attributes아니요라이브 알림을 초기화하는 데 사용되는 정적 데이터입니다. 알림에 필요한 데이터를 정의하는 자체 정의 스키마입니다.
event_updates아니요라이브 알림의 동적 콘텐츠입니다. 앱의 라이브 알림 내에 정의된 ContentState 인터페이스를 따라야 합니다.
Example Live Notification Payload
  {
      "key": "celtics-vs-lakers",
      "event": "start",
      "event_attributes": {
          "homeTeam": "Celtics",
          "awayTeam": "Lakers",
          "game": "Finals Game 1"
      },
      "event_updates": {
          "quarter": 1,
          "homeScore": 0,
          "awayScore": 0,
      }
  }

5. 라이브 알림 이벤트 처리

각 라이브 알림은 다음 이벤트에 응답해야 합니다:
이벤트설명필수 필드
start정적 및 동적 데이터로 라이브 알림을 시작합니다.event_attributes, event_updates
update새 동적 데이터로 라이브 알림을 업데이트합니다.event_updates
end라이브 알림을 종료하고 제거합니다.없음
NotificationServiceExtention.kt
val liveNotificationEvent = liveNotificationPayload.optString("event", "")

라이브 알림 시작

라이브 알림을 시작할 준비가 되면:
  • event_attributes를 설정하여 라이브 알림의 정적 데이터를 초기화합니다. 이 데이터는 라이브 알림의 수명 동안 변경되지 않습니다.
  • event_updates 데이터를 설정하여 라이브 알림의 동적 데이터를 초기화합니다. 이것은 라이브 알림의 수명 동안 변경될 수 있고 변경될 데이터입니다.
  • collapse_id를 사용하여 각 업데이트가 이전 업데이트를 재정의하도록 합니다. 이 ID는 라이브 알림에 고유해야 후속 업데이트가 동일한 알림에 반영됩니다.
curl
  curl -X "POST" "https://api.onesignal.com/notifications" \
       -H 'Authorization: key YOUR_REST_API_KEY' \
       -H 'Content-Type: application/json; charset=utf-8' \
       -d $'{
    "app_id": "YOUR_APP_ID",
    "isAndroid": true,
    "collapse_id": "THE_UNIQUE_ID_FOR_THIS_LIVE_NOTIFICATION",
    "data": {
      "live_notification": {
        "key": "progress",
        "event": "start",
        "event_attributes": {},
        "event_updates": {
          "current_progress": 0
        }
      }
    },
    "headings": {
      "en": "Start"
    },
    "contents": {
      "en": "Starting Live Notification"
    },
    "include_aliases": {
      "external_id": ["EID1", "EID2"]
    },
    "target_channel": "push"
  }'

라이브 알림 업데이트

먼저 시작한 경우 라이브 알림을 원하는 만큼 여러 번 업데이트할 수 있습니다.
  • event_updates 데이터를 설정하여 라이브 알림의 동적 데이터를 초기화합니다. 이것은 라이브 알림의 수명 동안 변경될 수 있고 변경될 데이터이며 라이브 알림의 콘텐츠를 무엇으로 업데이트할지 알려줍니다.
cURL 요청 예제
curl
  curl -X "POST" "https://api.onesignal.com/notifications" \
       -H 'Authorization: key YOUR_REST_API_KEY' \
       -H 'Content-Type: application/json; charset=utf-8' \
       -d $'{
    "app_id": "YOUR_APP_ID",
    "isAndroid": true,
    "collapse_id": "THE_UNIQUE_ID_FOR_THIS_LIVE_NOTIFICATION",
    "data": {
      "live_notification": {
        "key": "progress",
        "event": "update",
  			"event_attributes": {},
        "event_updates": {
          "current_progress": 80
        }
      }
    },
    "headings": {
      "en": "Update"
    },
    "contents": {
      "en": "Updating Live Notification"
    },
    "include_aliases": {
      "external_id": ["EID1", "EID2"]
    },
    "target_channel": "push"
  }'

라이브 알림 종료

cURL 요청 예제
curl
  curl -X "POST" "https://api.onesignal.com/notifications" \
       -H 'Authorization: key YOUR_REST_API_KEY' \
       -H 'Content-Type: application/json; charset=utf-8' \
       -d $'{
    "app_id": "YOUR_APP_ID",
    "isAndroid": true,
    "collapse_id": "THE_UNIQUE_ID_FOR_THIS_LIVE_NOTIFICATION",
    "data": {
      "live_notification": {
        "key": "progress",
        "event": "dismiss"
      }
    },
    "headings": {
      "en": "Dismissing"
    },
    "contents": {
      "en": "Dismissing Live Notification"
    },
    "include_aliases": {
      "external_id": ["EID1", "EID2"]
    },
    "target_channel": "push"
  }'

라이브 알림을 성공적으로 만들었습니다!관련 문서: