> ## 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 live notifications

> OneSignal Live Notificationsを使用して、Androidデバイス上で動的なリアルタイム通知を作成および更新します。単一の通知内で継続的に更新されるコンテンツを配信し、Android用のiOS Live Activitiesをシミュレートします。

OneSignalのAndroid Live Notificationsを使用すると、単一の通知にリアルタイム更新を送信でき、混乱を減らしてエンゲージメントを向上させることができます。これらの通知は永続的に残り、コンテンツを動的に更新します。スポーツスコア、ダウンロード進行状況、またはイベント追跡に最適です。

Live Notificationsを受信するには、Androidユーザーはプッシュ通知を有効にする必要があります。

## 要件

* アプリは最新バージョンの[OneSignal SDK](./mobile-sdk-setup)を使用する必要があります。
* Androidユーザーはプッシュ通知権限を有効にする必要があります。

***

## Live notificationsと標準プッシュの比較

通常のプッシュ通知は毎回新しい通知を送信しますが、Live Notificationsは時間の経過とともに更新される単一の通知を使用します。更新は、同じ`collapse_id`を使用して[Create Message API](/reference/create-message)を介して送信されます。

***

## 設定

### 1. Notification Service Extensionを実装する

`INotificationServiceExtension`を実装する`NotificationServiceExtension`クラスを作成します。このクラスは受信通知を傍受し、変更またはオーバーライドできます。

<Info>
  詳細については、[Android Notification Service Extension](./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. Live Notificationタイプを作成する

Live Notification Typeは、どのLive Notificationを開始するかを示します。

#### キーを定義する

Live Notificationsは`key`によって参照され、更新がどのようにルーティングされるかを決定します。

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

#### 通知チャネルを作成する

チャネルは通知の動作（サウンド、バイブレーション、外観）を定義します。Live Notificationタイプ用のチャネルを作成する必要があります。推奨事項：

* 進行状況通知には低重要度
* バッジを無効にする
* サウンドとバイブレーションを最小限に抑える

詳細については、[Android Notification Channel Categories](./android-notification-categories)を参照してください。

#### Live Notificationをデザインする

Live Notificationをデザインする際、各更新タイプに対して通知デザインを作成する柔軟性があります。作成する各デザインには特定のタイプを割り当てる必要があり、Live Notificationのさまざまなプレゼンテーションが可能になります。

```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 custom notification layout](https://developer.android.com/develop/ui/views/notifications/custom-notification)を参照してください。
</Info>

### 4. Live Notificationペイロードを抽出する

Live Notificationsは、構造化されたコンテンツを渡すために`additional_data`フィールドを使用します。

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

#### Live Notificationスキーマ

| Property           | Required | Description                                                                             |
| ------------------ | -------- | --------------------------------------------------------------------------------------- |
| `key`              | Yes      | 正しい通知UIを読み込むために使用されます。                                                                  |
| `event`            | Yes      | Live Notificationに対して実行するアクション。                                                         |
| `event_attributes` | No       | Live Notificationを初期化するために使用される静的データ。通知に必要なデータを定義する自己定義スキーマ。                            |
| `event_updates`    | No       | Live Notificationの動的コンテンツ。アプリのLive Notification内で定義された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. Live Notificationイベントを処理する

各Live Notificationは、以下のイベントに応答する必要があります：

| Event    | Description                          | Required fields                     |
| -------- | ------------------------------------ | ----------------------------------- |
| `start`  | 静的データと動的データでLive Notificationを開始します。 | `event_attributes`, `event_updates` |
| `update` | 新しい動的データでLive Notificationを更新します。    | `event_updates`                     |
| `end`    | Live Notificationを終了して削除します。         | なし                                  |

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

***

## Live Notificationを開始する

Live Notificationを開始する準備ができたら：

* `event_attributes`を設定して、Live Notificationの静的データを初期化します。このデータは、Live Notificationの存続期間中は変更されません。
* `event_updates`データを設定して、Live Notificationの動的データを初期化します。これは、Live Notificationの存続期間中に変更される可能性があり、実際に変更されるデータです。
* [`collapse_id`](./push#collapse-id)を使用して、各更新が前の更新を上書きすることを確認します。このIDは、後続の更新が同じ通知に反映されるように、Live Notificationに固有である必要があります。

```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"
  }'
```

***

## Live Notificationを更新する

最初に開始されている限り、Live Notificationは何度でも更新できます。

* `event_updates`データを設定して、Live Notificationの動的データを初期化します。これは、Live Notificationの存続期間中に変更される可能性があり、実際に変更されるデータであり、Live Notificationのコンテンツを何で更新するかを通知します。

**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"
  }'
```

## Live Notificationを終了する

**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>
  Live Notificationの作成に成功しました！

  関連ドキュメント：

  * [Android Notification Service Extension](./service-extensions#android-notification-service-extension)
  * [Android SDK Setup](./mobile-sdk-setup)
  * [Create Message API](/reference/create-message)
</Check>

***
