> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Android 라이브 알림

> OneSignal 라이브 알림을 사용하여 Android 기기에서 동적인 실시간 알림을 생성하고 업데이트하세요. 단일 알림 내에서 지속적으로 업데이트되는 콘텐츠를 제공하여 Android용 iOS 라이브 활동을 시뮬레이션합니다.

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

라이브 알림을 받으려면 Android 사용자는 푸시 알림을 활성화해야 합니다.

## 요구 사항

* 앱은 최신 버전의 [OneSignal SDK](./mobile-sdk-setup)를 사용해야 합니다.
* Android 사용자는 푸시 알림 권한을 활성화해야 합니다.

***

## 라이브 알림 vs. 표준 푸시

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

***

## 구성

### 1. 알림 서비스 확장 구현

`INotificationServiceExtension`을 구현하는 `NotificationServiceExtension` 클래스를 만듭니다. 이 클래스는 들어오는 알림을 가로채서 수정하거나 재정의할 수 있습니다.

<Info>
  자세한 내용은 [Android 알림 서비스 확장](./service-extensions#android-notification-service-extension)을 참조하세요.
</Info>

```kotlin NotificationServiceExtention.kt theme={null}
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에 확장 추가

<CodeGroup>
  ```xml AndroidManifest.xml theme={null}
    <meta-data android:name="com.onesignal.NotificationServiceExtension"
                android:value="com.onesignal.sample.android.NotificationServiceExtension" />
  ```

  ```xml Example AndroidManifest.xml theme={null}
  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools">

      <application
          android:allowBackup="true"
          android:dataExtractionRules="@xml/data_extraction_rules"
          android:fullBackupContent="@xml/backup_rules"
          android:icon="@mipmap/ic_launcher"
          android:name=".MainApplication"
          android:label="@string/app_name"
          android:roundIcon="@mipmap/ic_launcher_round"
          android:supportsRtl="true"
          android:theme="@style/Theme.OneSignalAndroidSample"
          tools:targetApi="31">
          <meta-data android:name="com.onesignal.NotificationServiceExtension"
              android:value="com.onesignal.sample.android.NotificationServiceExtension" />
          <activity
              android:name=".MainActivity"
              android:exported="true">
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

  </manifest>
  ```
</CodeGroup>

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

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

#### 키 정의

라이브 알림은 `key`로 참조되며, 이는 업데이트가 라우팅되는 방법을 결정합니다.

```kotlin NotificationServiceExtention.kt theme={null}
private const val PROGRESS_LIVE_NOTIFICATION = "progress"
```

#### 알림 채널 만들기

채널은 알림의 동작(소리, 진동, 모양)을 정의합니다. 라이브 알림 유형에 대한 채널을 만들어야 합니다. 권장 사항:

* 진행 알림에는 낮은 중요도 사용
* 배지 비활성화
* 소리 및 진동을 최소화

자세한 내용은 [Android 알림 채널 카테고리](./android-notification-categories)를 참조하세요.

#### 라이브 알림 디자인

라이브 알림을 디자인할 때 각 업데이트 유형에 대한 알림 디자인을 만들 수 있는 유연성이 있습니다. 만드는 각 디자인에는 특정 유형이 할당되어야 하므로 라이브 알림의 다양한 표현이 가능합니다.

```kotlin NotificationServiceExtention.kt theme={null}
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")
    }
```

**디자인 고려 사항:**

* 작은 아이콘 및 강조 색상
* 큰 아이콘
* 큰 그림
* 작업 버튼

<Info>
  고급 디자인 옵션은 [Android 사용자 지정 알림 레이아웃](https://developer.android.com/develop/ui/views/notifications/custom-notification)을 참조하세요.
</Info>

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

라이브 알림은 `additional_data` 필드를 사용하여 구조화된 콘텐츠를 전달합니다.

```kotlin NotificationServiceExtention.kt theme={null}
val additionalData = event.notification.additionalData
val liveNotificationPayload = additionalData?.optJSONObject("live_notification")
```

#### 라이브 알림 스키마

| 속성                 | 필수  | 설명                                                               |
| ------------------ | --- | ---------------------------------------------------------------- |
| `key`              | 예   | 올바른 알림 UI를 로드하는 데 사용됩니다.                                         |
| `event`            | 예   | 라이브 알림에서 수행할 작업입니다.                                              |
| `event_attributes` | 아니요 | 라이브 알림을 초기화하는 데 사용되는 정적 데이터입니다. 알림에 필요한 데이터를 정의하는 자체 정의 스키마입니다.  |
| `event_updates`    | 아니요 | 라이브 알림의 동적 콘텐츠입니다. 앱의 라이브 알림 내에 정의된 ContentState 인터페이스를 따라야 합니다. |

```json Example Live Notification Payload theme={null}
  {
      "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`    | 라이브 알림을 종료하고 제거합니다.         | 없음                                  |

```kotlin NotificationServiceExtention.kt theme={null}
val liveNotificationEvent = liveNotificationPayload.optString("event", "")
```

***

## 라이브 알림 시작

라이브 알림을 시작할 준비가 되면:

* `event_attributes`를 설정하여 라이브 알림의 정적 데이터를 초기화합니다. 이 데이터는 라이브 알림의 수명 동안 변경되지 않습니다.
* `event_updates` 데이터를 설정하여 라이브 알림의 동적 데이터를 초기화합니다. 이것은 라이브 알림의 수명 동안 변경될 수 있고 변경될 데이터입니다.
* [`collapse_id`](./push#collapse-id)를 사용하여 각 업데이트가 이전 업데이트를 재정의하도록 합니다. 이 ID는 라이브 알림에 고유해야 후속 업데이트가 동일한 알림에 반영됩니다.

```curl curl theme={null}
  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 theme={null}
  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 theme={null}
  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"
  }'
```

***

<Check>
  라이브 알림을 성공적으로 만들었습니다!

  관련 문서:

  * [Android 알림 서비스 확장](./service-extensions#android-notification-service-extension)
  * [Android SDK 설정](./mobile-sdk-setup)
  * [Create Message API](/reference/create-message)
</Check>

***
