Skip to content

プッシュ通知

プッシュ通知を使用すると、重要なイベントが発生したときにアプリから通知を送ることができます。新しいインスタントメッセージを配信したり、ニュース速報を送信したり、ユーザーのお気に入りのテレビ番組の最新エピソードがダウンロードしてオフライン視聴する準備ができたときに、プッシュ通知を送信することがあります。また、アプリケーションは必要なときにのみ起動するため、バックグラウンドフェッチよりも効率的です。

前提条件

この機能を使用する前に、Android Braze SDKを統合する必要があります。

内蔵機能

以下の機能がBraze Android SDKに組み込まれている。その他のプッシュ通知機能を使うには、アプリのプッシュ通知を設定する必要がある。

プッシュ通知のライフサイクルについて

次のフローチャートは、Brazeが権限プロンプト、トークン生成、メッセージ配信などのプッシュ通知のライフサイクルをどのように処理しているかを示している。

---
config:
  theme: neutral
---
flowchart TD

%% Permission flow
subgraph Permission[Push Permissions]
    B{Android version of the device?}
    B -->|Android 13+| C["requestPushPermissionPrompt() called"]
    B -->|Android 12 and earlier| D[No permissions required]
    
    %% Connect Android 12 path to Braze state
    D --> H3[Braze: user subscription state]
    H3 --> J3[Defaults to 'subscribed' when user profile created]
    
    C --> E{Did the user grant push permission?}
    E -->|Yes| F[POST_NOTIFICATIONS permission granted]
    E -->|No| G[POST_NOTIFICATIONS permission denied]
    
    %% Braze subscription state updates
    F --> H1[Braze: user subscription state]
    G --> H2[Braze: user subscription state]
    
    H1 --> I1{Automatically opt in after permission granted?}
    I1 -->|true| J1[Set to 'opted-in']
    I1 -->|false| J2[Remains 'subscribed']
    
    H2 --> K1[Remains 'subscribed'<br/>or 'unsubscribed']
    
    %% Subscription state legend
    subgraph BrazeStates[Braze subscription states]
        L1['Subscribed' - default state<br/>when user profile created]
        L2['Opted-in' - user explicitly<br/>wants push notifications]
        L3['Unsubscribed' - user explicitly<br/>opted out of push]
    end
    
    %% Note about user-level states
    note1[Note: These states are user-level<br/>and apply across all devices for the user]
    
    %% Connect states to legend
    J1 -.-> L2
    J2 -.-> L1
    J3 -.-> L1
    K1 -.-> L3
    note1 -.-> BrazeStates
end

%% Styling
classDef permissionClass fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
classDef tokenClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
classDef sdkClass fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef configClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef displayClass fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef deliveryClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef brazeClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px

class A,B,C,E,F,G permissionClass
class H,I tokenClass
class J,K sdkClass
class N,O,P configClass
class R,S,S1,T,U,V displayClass
class W,X,X1,X2,Y,Z deliveryClass
class H1,H2,H3,I1,J1,J2,J3,K1,L1,L2,L3,note1 brazeClass
---
config:
  theme: neutral
---
flowchart TD

%% Token generation flow
subgraph Token[Token Generation]
    H["Braze SDK initialized"] --> Q{Is FCM auto-registration enabled?}
    Q -->|Yes| L{Is required configuration present?}
    Q -->|No| M[No FCM token generated]
    L -->|Yes| I[Generate FCM token]
    L -->|No| M
    I --> K[Register token with Braze]

    %% Configuration requirements
    subgraph Config[Required configuration]
        N['google-services.json' file is present]
        O['com.google.firebase:firebase-messaging' in gradle]
        P['com.google.gms.google-services' plugin in gradle]
    end

    %% Connect config to check
    N -.-> L
    O -.-> L
    P -.-> L
end

%% Styling
classDef permissionClass fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
classDef tokenClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
classDef sdkClass fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef configClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef displayClass fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef deliveryClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef brazeClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px

class A,B,C,E,F,G permissionClass
class H,I tokenClass
class J,K sdkClass
class N,O,P configClass
class R,S,S1,T,U,V displayClass
class W,X,X1,X2,Y,Z deliveryClass
class H1,H2,H3,I1,J1,J2,J3,K1,L1,L2,L3,note1 brazeClass
---
config:
  theme: neutral
  fontSize: 10
---
flowchart TD

subgraph Display[Push Display]
    %% Push delivery flow
    W[Push sent to FCM servers] --> X{Did FCM receive push?}
    X -->|App is terminated| Y[FCM cannot deliver push to the app]
    X -->|Delivery conditions met| X1[App receives push from FCM]
    X1 --> X2[Braze SDK receives push]
    X2 --> R[Push type?]

    %% Push Display Flow
    R -->|Standard push| S{Is push permission required?}
    R -->|Silent push| T[Braze SDK processes silent push]
    S -->|Yes| S1{Did the user grant push permission?}
    S -->|No| V[Notification is shown to the user]
    S1 -->|Yes| V
    S1 -->|No| U[Notification is not shown to the user]
end

%% Styling
classDef permissionClass fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
classDef tokenClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
classDef sdkClass fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef configClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef displayClass fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef deliveryClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef brazeClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px

class A,B,C,E,F,G permissionClass
class H,I tokenClass
class J,K sdkClass
class N,O,P configClass
class R,S,S1,T,U,V displayClass
class W,X,X1,X2,Y,Z deliveryClass
class H1,H2,H3,I1,J1,J2,J3,K1,L1,L2,L3,note1 brazeClass

プッシュ通知の設定

レート制限

Firebase Cloud Messaging (FCM) API には、1分当たりに600,000リクエストというデフォルトのレート制限があります。この制限に達した場合、Brazeは数分後に自動的に再試行します。増加をリクエストするには、Firebaseサポートに連絡してください。

ステップ 1: Firebase をプロジェクトに追加する

最初に、FirebaseをAndroidプロジェクトに追加します。手順については、GoogleのFirebaseセットアップガイドを参照してください。

ステップ 2:Cloud Messaging を依存関係に追加する

次に、Cloud Messaging ライブラリをプロジェクトの依存関係に追加します。Android プロジェクトで build.gradle を開き、dependencies ブロックに次の行を追加します。

1
implementation "google.firebase:firebase-messaging:+"

依存関係は次のようになります。

1
2
3
4
dependencies {
  implementation project(':android-sdk-ui')
  implementation "com.google.firebase:firebase-messaging:+"
}

ステップ3:Firebase Cloud Messaging API を有効にする

Google Cloud で、Android アプリが使用しているプロジェクトを選択し、Firebase Cloud Messaging API を有効にします。

有効になっている Firebase Cloud Messaging API

ステップ 4: サービスアカウントを作成する

次に、新しいサービスアカウントを作成し、FCM トークンの登録時に Braze が許可された API 呼び出しを行えるようにします。Google Cloud で、[サービスアカウント] に移動し、プロジェクトを選択します。[サービスアカウント] ページで [サービスアカウントの作成] を選択します。

「サービス アカウントの作成」が強調表示されたプロジェクトのサービス アカウントのホーム ページ。

サービスアカウント名、ID、説明を入力して、[作成して続行] を選択します。

[サービスアカウントの詳細] のフォーム。

[ロール] フィールドで、ロールのリストから [Firebase Cloud Messaging API 管理者] を見つけて選択します。アクセスをより制限する場合は、cloudmessaging.messages.create 権限を持つカスタムロールを作成し、代わりにリストからそれを選択します。[完了] を選択します。

[Firebase Cloud Messaging API 管理者] がロールとして選択されている、「このサービスアカウントにプロジェクトへのアクセス権を付与」するためのフォーム。

ステップ 5: JSON認証情報を生成する

次に、FCM サービスアカウントの JSON 認証情報を生成します。Google Cloud IAM & Admin で、[サービスアカウント] に移動し、プロジェクトを選択します。先ほど作成した FCM サービスアカウントを見つけて、[アクション] > [キーの管理] を選択します。

[アクション] メニューが開いた状態の、プロジェクトのサービスアカウントホームページ。

[キーの追加] > [新しいキーを作成] を選択します。

[キーを追加] メニューが開いた状態の選択されたサービスアカウント。

[JSON] を選択し、[作成] を選択します。FCM プロジェクト ID とは異なる Google Cloud のプロジェクト ID を使用してサービスアカウントを作成した場合は、JSON ファイルで project_id に割り当てられた値を手動で更新する必要があります。

キーをどこにダウンロードしたかを覚えておいてください。次のステップで必要になります。

「JSON」が選択された秘密キーの作成フォームです。

ステップ 6:JSON の認証情報を Braze にアップロードする

次に、JSON 認証情報を Braze ダッシュボードにアップロードします。Braze で、[設定] > [アプリの設定] を選択します。

[アプリ設定] が強調表示された状態で Braze で [設定] メニューが開いています。

Android アプリの [プッシュ通知設定] で [Firebase] を選択し、[JSON ファイルのアップロード] を選択して、先ほど生成した認証情報をアップロードします。完了したら、[保存] を選択します。

「プッシュ通知設定」のフォームで、プッシュプロバイダーとして「Firebase」が選択されています。

ステップ 7:トークンの自動登録を設定する

ユーザーの 1 人がプッシュ通知をオプトインした場合、アプリはそのユーザーにプッシュ通知を送信する前に、ユーザーのデバイス上で FCM トークンを生成する必要があります。Braze SDK を使用すると、プロジェクトの Braze 構成ファイルで各ユーザーのデバイスで FCM トークンの自動登録を有効にすることができます。

まず Firebase Console に移動し、プロジェクトを開いて、[設定] > [プロジェクト設定] を選択します。

[設定] メニューが開いた状態の Firebase プロジェクト。

[Cloud Messaging] を選択し、[Firebase Cloud Messaging API (V1)] で [送信者 ID] フィールドの数字をコピーします。

[送信者 ID] が強調表示されている Firebase プロジェクトの「Cloud Messaging」ページ。

次に、Android Studio プロジェクトを開き、Firebase 送信者 ID を使用して、braze.xml または BrazeConfig 内で FCM トークンの自動登録を有効にします。

FCM トークンの自動登録を設定するには、braze.xml ファイルに以下の行を追加します。

1
2
<bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">FIREBASE_SENDER_ID</string>

FIREBASE_SENDER_ID を Firebase プロジェクトの設定からコピーした値に置き換えます。braze.xml は次のようになります。

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string translatable="false" name="com_braze_api_key">12345ABC-6789-DEFG-0123-HIJK456789LM</string>
  <bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">603679405392</string>
</resources>

自動FCMトークン登録を構成するには、次の行をBrazeConfigに追加します:

1
2
.setIsFirebaseCloudMessagingRegistrationEnabled(true)
.setFirebaseCloudMessagingSenderIdKey("FIREBASE_SENDER_ID")
1
2
.setIsFirebaseCloudMessagingRegistrationEnabled(true)
.setFirebaseCloudMessagingSenderIdKey("FIREBASE_SENDER_ID")

FIREBASE_SENDER_ID を Firebase プロジェクトの設定からコピーした値に置き換えます。BrazeConfig は次のようになります。

1
2
3
4
5
6
7
8
9
10
BrazeConfig brazeConfig = new BrazeConfig.Builder()
  .setApiKey("12345ABC-6789-DEFG-0123-HIJK456789LM")
  .setCustomEndpoint("sdk.iad-01.braze.com")
  .setSessionTimeout(60)
  .setHandlePushDeepLinksAutomatically(true)
  .setGreatNetworkDataFlushInterval(10)
  .setIsFirebaseCloudMessagingRegistrationEnabled(true)
  .setFirebaseCloudMessagingSenderIdKey("603679405392")
  .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
6
7
8
9
10
val brazeConfig = BrazeConfig.Builder()
  .setApiKey("12345ABC-6789-DEFG-0123-HIJK456789LM")
  .setCustomEndpoint("sdk.iad-01.braze.com")
  .setSessionTimeout(60)
  .setHandlePushDeepLinksAutomatically(true)
  .setGreatNetworkDataFlushInterval(10)
  .setIsFirebaseCloudMessagingRegistrationEnabled(true)
  .setFirebaseCloudMessagingSenderIdKey("603679405392")
  .build()
Braze.configure(this, brazeConfig)

ステップ 8アプリケーションクラスの自動リクエストを削除する

サイレントプッシュ通知を送信するたびにBrazeが不要なネットワークリクエストをトリガーするのを防ぐには、Application クラスのonCreate() メソッドで設定されている自動ネットワークリクエストをすべて削除する。詳細については、Android 開発者リファレンス:アプリケーションを参照してください。

通知を表示する

ステップ 1: Braze Firebase メッセージングサービスを登録する

新規、既存、またはBraze以外のFirebaseメッセージングサービスを作成することができる。特定のニーズに最も適したものを選択する。

Braze には、プッシュ受信インテントと開封インテントを処理するサービスが含まれています。BrazeFirebaseMessagingService クラスは AndroidManifest.xml に登録する必要があります。

1
2
3
4
5
6
<service android:name="com.braze.push.BrazeFirebaseMessagingService"
  android:exported="false">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
  </intent-filter>
</service>

通知コードでは、BrazeFirebaseMessagingService を使用して、オープンアクションとクリックアクションのトラッキングも処理します。このサービスが正しく機能するには、AndroidManifest.xml に登録する必要があります。また、Brazeはシステムからの通知に固有のキーを付けているため、システムから送信された通知のみを表示することができます。他の FCM サービスから送信される通知を表示するために、追加のサービスを個別に登録することもできます。を参照のこと。 AndroidManifest.xmlを参照のこと。

Firebase Messaging Service がすでに登録されている場合は、RemoteMessage オブジェクトをBrazeFirebaseMessagingService.handleBrazeRemoteMessage() 経由でBraze に渡すことができます。このメソッドは RemoteMessage オブジェクトが Braze から発信された場合にのみ通知を表示し、そうでない場合は無視します。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MyFirebaseMessagingService extends FirebaseMessagingService {
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    if (BrazeFirebaseMessagingService.handleBrazeRemoteMessage(this, remoteMessage)) {
      // This Remote Message originated from Braze and a push notification was displayed.
      // No further action is needed.
    } else {
      // This Remote Message did not originate from Braze.
      // No action was taken and you can safely pass this Remote Message to other handlers.
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
class MyFirebaseMessagingService : FirebaseMessagingService() {
  override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    super.onMessageReceived(remoteMessage)
    if (BrazeFirebaseMessagingService.handleBrazeRemoteMessage(this, remoteMessage)) {
      // This Remote Message originated from Braze and a push notification was displayed.
      // No further action is needed.
    } else {
      // This Remote Message did not originate from Braze.
      // No action was taken and you can safely pass this Remote Message to other handlers.
    }
  }
}

使用したい別の Firebase メッセージングサービスがある場合は、アプリケーションが Braze からではないプッシュを受信した場合に呼び出すフォールバック Firebase メッセージングサービスを指定することもできます。

braze.xml で次のように指定します。

1
2
<bool name="com_braze_fallback_firebase_cloud_messaging_service_enabled">true</bool>
<string name="com_braze_fallback_firebase_cloud_messaging_service_classpath">com.company.OurFirebaseMessagingService</string>

または、ランタイム設定で設定します:

1
2
3
4
5
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setFallbackFirebaseMessagingServiceEnabled(true)
        .setFallbackFirebaseMessagingServiceClasspath("com.company.OurFirebaseMessagingService")
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
val brazeConfig = BrazeConfig.Builder()
        .setFallbackFirebaseMessagingServiceEnabled(true)
        .setFallbackFirebaseMessagingServiceClasspath("com.company.OurFirebaseMessagingService")
        .build()
Braze.configure(this, brazeConfig)

ステップ 2:小さなアイコンをデザインガイドラインに準拠させる

Android 通知アイコンの一般的な情報については、通知の概要 をご覧ください。

Android N 以降、色を使った小さな通知アイコンアセットは更新または削除する必要があります。Android システム (Braze SDK ではない) は、アクションアイコンと小さな通知アイコンの非アルファチャネルと透明チャネルをすべて無視します。つまり、Android は小さな通知アイコンの透明領域を除くすべての部分をモノクロに変換します。

適切に表示される通知用スモールアイコンアセットを作成する:

  • 画像から白以外のすべての色を削除します。
  • アセットの他のすべての非白色領域は透明である必要があります。

次の図の大小アイコンは、適切にデザインされたアイコンの例です。

大きなアイコンの隣に「ねえ、バーに向かっているけど…」というメッセージが表示されると、右下に小さなアイコンが表示されます

ステップ 3:通知アイコンを設定する

braze.xmlでアイコンを指定する

Braze では、braze.xml 内で描画可能なリソースを指定することで、通知アイコンを設定できます。

1
2
<drawable name="com_braze_push_small_notification_icon">REPLACE_WITH_YOUR_ICON</drawable>
<drawable name="com_braze_push_large_notification_icon">REPLACE_WITH_YOUR_ICON</drawable>

小さな通知アイコンの設定は必須です。設定しない場合、Braze はデフォルトで小さな通知アイコンとしてアプリケーションアイコンを使用しますが、これは最適に表示されない可能性があります。

大きな通知アイコンの設定は任意ですが、推奨されます。

アイコンのアクセントカラーの指定

通知アイコンのアクセントカラーは、braze.xml でオーバーライドできます。色を指定しない場合、デフォルトの色は Lollipop がシステム通知に使用するのと同じグレーになります。

1
<integer name="com_braze_default_notification_accent_color">0xFFf33e3e</integer>

オプションでカラーリファレンスを使用することもできます。

1
<color name="com_braze_default_notification_accent_color">@color/my_color_here</color>

ステップ4: ディープリンクを追加する

ディープリンクの自動オープンを有効にする

プッシュ通知がクリックされたときに Braze がアプリとディープリンクを自動的に開くようにするには、braze.xmlcom_braze_handle_push_deep_links_automaticallytrue に設定します。

1
<bool name="com_braze_handle_push_deep_links_automatically">true</bool>

このフラグは、実行時設定 で設定することもできます。

1
2
3
4
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setHandlePushDeepLinksAutomatically(true)
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
val brazeConfig = BrazeConfig.Builder()
        .setHandlePushDeepLinksAutomatically(true)
        .build()
Braze.configure(this, brazeConfig)

ディープリンクをカスタムで処理する場合は、Braze からのプッシュ受信およびオープンインテントをリッスンするプッシュコールバックを作成する必要があります。詳しくは、プッシュ・イベントにコールバックを使うを参照のこと。

カスタムディープリンクの作成

まだアプリにディープリンクを追加していない場合は、Android開発者のドキュメントにあるディープリンクに関する指示に従ってほしい。ディープリンクの詳細については、FAQ の記事を参照してください。

ディープリンクの追加

Braze ダッシュボードは、通知がクリックされたときに開くプッシュ通知キャンペーンとキャンバスでのディープリンクまたは Web URL の設定をサポートしています。

Braze ダッシュボードの「On Click Behavior」設定。ドロップダウンから「Deep Link Into Application」を選択。

バックスタックの動作のカスタマイズ

Android SDK のデフォルトでは、プッシュのディープリンクを辿ると、ホストアプリのメインのランチャーアクティビティがバックスタックに配置されます。Braze では、メインのランチャーアクティビティの代わりにバックスタックで開くカスタムアクティビティを設定したり、バックスタックを完全に無効にしたりすることができます。

たとえば、ランタイム設定 を使用して、YourMainActivity というアクティビティをバックスタックアクティビティとして設定するには、次のようにします。

1
2
3
4
5
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setPushDeepLinkBackStackActivityEnabled(true)
        .setPushDeepLinkBackStackActivityClass(YourMainActivity.class)
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
val brazeConfig = BrazeConfig.Builder()
        .setPushDeepLinkBackStackActivityEnabled(true)
        .setPushDeepLinkBackStackActivityClass(YourMainActivity.class)
        .build()
Braze.configure(this, brazeConfig)

braze.xml の同等の設定を参照してください。クラス名は Class.forName() で返されるものと同じでなければならないことに注意してください。

1
2
<bool name="com_braze_push_deep_link_back_stack_activity_enabled">true</bool>
<string name="com_braze_push_deep_link_back_stack_activity_class_name">your.package.name.YourMainActivity</string>

ステップ5:通知チャネルを定義する

Braze Android SDK はAndroid 通知チャネル をサポートしています。Braze の通知に通知チャネルの ID が含まれていない場合、または Braze の通知に無効なチャネル ID が含まれている場合、Braze は SDK で定義されているデフォルトの通知チャネルで通知を表示します。Braze ユーザーは、プラットフォーム内でAndroid 通知チャネル を使用して通知をグループ化します。

デフォルトの Braze 通知チャネルのユーザー向けの名前を設定するには、BrazeConfig.setDefaultNotificationChannelName() を使用します。

デフォルトの Braze 通知チャネルのユーザー向けの説明を設定するには、BrazeConfig.setDefaultNotificationChannelDescription() を使用します。

Android push object パラメータを使用してAPI キャンペーンを更新し、notification_channel フィールドを含めます。このフィールドが指定されていない場合、Braze はダッシュボードフォールバック チャネルID を持つ通知ペイロードを送信します。

デフォルトの通知チャネル以外、Braze はチャネルを作成しません。他のすべてのチャネルは、ホストアプリでプログラムで定義してから、Braze ダッシュボードに入力する必要があります。

デフォルトのチャネル名と説明も braze.xml で設定できます。

1
2
<string name="com_braze_default_notification_channel_name">Your channel name</string>
<string name="com_braze_default_notification_channel_description">Your channel description</string>

ステップ 6:通知の表示と分析をテストする

表示のテスト

この時点で、Braze から送信された通知を表示できるはずです。これをテストするには、Braze ダッシュボードの [キャンペーン] ページにアクセスし、プッシュ通知キャンペーンを作成します。[Android プッシュ] を選択し、メッセージをデザインします。次に、作成画面で目のアイコンをクリックしてテスト送信者を取得します。現在のユーザーのユーザー ID またはメールアドレスを入力し、[テストを送信] をクリックします。デバイスにプッシュが表示されます。

Braze ダッシュボードのプッシュ通知キャンペーンの'Test' タブ。

プッシュ表示に関する問題については、トラブルシューティングガイドを参照してください。

分析のテスト

この時点で、プッシュ通知の開封に関する分析ログも届いているはずです。届いた通知をクリックすると、キャンペーン結果ページの [直接開封数] の値が 1 増えます。プッシュ分析の内訳については、プッシュレポートの記事をご覧ください。

プッシュアナリティクスに関する問題については、トラブルシューティングガイドを参照してください。

コマンドラインからのテスト

コマンドラインインターフェイスを介してアプリ内通知とプッシュ通知をテストする場合は、cURL とメッセージAPI を介して端末から単一の通知を送信できます。次のフィールドをテストケースの正しい値に置き換える必要があります。

  • YOUR_API_KEY ([設定] > [API キー]に移動)
  • YOUR_EXTERNAL_USER_ID ([ユーザーを検索] ページでプロファイルを検索)
  • YOUR_KEY1 (省略可能)
  • YOUR_VALUE1 (省略可能)
1
2
3
4
5
6
7
8
9
10
11
12
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {YOUR_API_KEY}" -d '{
  "external_user_ids":["YOUR_EXTERNAL_USER_ID"],
  "messages": {
    "android_push": {
      "title":"Test push title",
      "alert":"Test push",
      "extra": {
        "YOUR_KEY1":"YOUR_VALUE1"
      }
    }  
  }
}' https://rest.iad-01.braze.com/messages/send

この例では、US-01 インスタンスを使用しています。このインスタンスを使用していない場合は、US-01 エンドポイントを [自分のエンドポイント] に置き換えてください。

会話のプッシュ通知

人と会話のイニシアチブは、スマートフォンのシステム上で人との会話を向上させることを目的とした、複数年にわたる Android の取り組みです。人との会話を優先する理由は、他のユーザーとのコミュニケーションや対話が、あらゆるユーザー層にわたる大多数のユーザーにとって、依然として最も価値のある重要な機能分野であるからです。

使用要件

  • この通知タイプには、Braze Android SDK v15.0.0 以降と Android 11 以降が搭載されたデバイスが必要です。
  • サポートされていないデバイスや SDK は、標準のプッシュ通知にフォールバックします。

この機能は、Braze REST API 経由でのみ利用できます。詳細については、Android プッシュオブジェクトを参照してください。

FCMクォータ超過エラー

Firebase Cloud Messaging (FCM) の上限を超えると、Google は “quota exceeded” エラーを返す。FCM のデフォルトの制限は、1分あたり 600,000 リクエストです。Brazeは、Googleが推奨するベストプラクティスに従って送信を再試行する。しかし、このようなエラーが大量に発生すると、送信時間が数分長くなることがある。潜在的な影響を軽減するために、Braze はレート制限を超えていることを示すアラートと、エラーを防ぐために実行できるステップをユーザーに送信します。

現在の上限を確認するには、Google Cloud Console>API & Services>Firebase Cloud Messaging API>Quotas & System Limitsにアクセスするか、FCM API Quotasページにアクセスする。

ベストプラクティス

このようなエラーの発生を抑えるために、以下のベストプラクティスを推奨する。

FCMにレート制限の引き上げを要請する。

FCMにレート制限の引き上げを要求するには、Firebaseサポートに直接連絡するか、次のようにする:

  1. FCM API Quotasのページに行く。
  2. 1分あたりの送信要求クォータを見つける。
  3. クォータの編集を選択する。
  4. 新しい値を入力し、リクエストを送信する。

Braze経由でグローバルレート制限をリクエストする

Androidプッシュ通知のワークスペース全体の制限を適用するには、Brazeサポートに連絡する。

レート制限

プッシュ通知にはレート制限があるため、アプリケーションで必要なだけ送信しても構いません。iOS と Apple Push Notification service (APNs) サーバーが配信頻度を制御するため、送信しすぎても問題が発生することはありません。プッシュ通知がスロットリングされている場合、デバイスが次にキープアライブパケットを送信するか、別の通知を受信するまで遅延する可能性があります。

プッシュ通知の設定

ステップ1:APN トークンをアップロードする

Before you can send an iOS push notification using Braze, you need to upload your .p8 push notification file, as described in Apple’s developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID. You’ll also need to specify whether to send notifications to your app’s development or production environment, which is defined by its provisioning profile.
  8. When you’re finished, select Save.

ステップ2: プッシュ機能を有効にする

Xcode で、メインアプリのターゲットの署名 & 機能セクションに移動しプッシュ通知機能を追加します。

Xcode プロジェクトの「署名 & 機能」セクション

ステップ 3:プッシュハンドリングの設定

Swift SDK を使用して、Braze から受信したリモート通知の処理を自動化できます。これはプッシュ通知を処理する最も簡単な方法であり、推奨される処理方法です。

ステップ 3.1:push プロパティーでの自動化の有効化

自動プッシュ統合を有効にするには、push 設定のautomation プロパティをtrue に設定する:

1
2
let configuration = Braze.Configuration(apiKey: "{YOUR-BRAZE-API-KEY}", endpoint: "{YOUR-BRAZE-API-ENDPOINT}")
configuration.push.automation = true
1
2
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{YOUR-BRAZE-API-KEY}" endpoint:@"{YOUR-BRAZE-API-ENDPOINT}"];
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];

これにより、SDK に次のことが指示されます。

  • プッシュ通知用のアプリケーションをシステムに登録する。
  • 初期化時にプッシュ通知の認証/許可を要求する。
  • プッシュ通知関連のシステム・デリゲート・メソッドの実装を動的に提供する。

ステップ 3.2:個々の設定の上書き(オプション)

よりきめ細かいコントロールのために、各オートメーションステップを個別に有効または無効にすることができます

1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = true
configuration.push.automation.requestAuthorizationAtLaunch = false
1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];
configuration.push.automation.requestAuthorizationAtLaunch = NO;

使用可能なすべてのオプションについては Braze.Configuration.Push.Automation を、オートメーション動作の詳細については automation を参照してください。

ステップ 3.1:APNでプッシュ通知に登録する

ユーザーのデバイスがAPNに登録できるように、アプリのapplication:didFinishLaunchingWithOptions: デリゲート・メソッド内に適切なコード・サンプルを含める。アプリケーションのメインスレッドですべてのプッシュ統合コードを呼び出すようにしてください。

Braze には、プッシュアクションボタンをサポートするデフォルトのプッシュカテゴリーも用意されており、プッシュ登録コードに手動で追加する必要があります。その他の統合ステップについては、プッシュアクションボタンを参照のこと。

アプリのデリゲートのapplication:didFinishLaunchingWithOptions: メソッドに以下のコードを追加する。

1
2
3
4
5
6
7
8
9
10
11
application.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(Braze.Notifications.categories)
center.delegate = self
var options: UNAuthorizationOptions = [.alert, .sound, .badge]
if #available(iOS 12.0, *) {
  options = UNAuthorizationOptions(rawValue: options.rawValue | UNAuthorizationOptions.provisional.rawValue)
}
center.requestAuthorization(options: options) { granted, error in
  print("Notification authorization, granted: \(granted), error: \(String(describing: error))")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[application registerForRemoteNotifications];
UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;
[center setNotificationCategories:BRZNotifications.categories];
center.delegate = self;
UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
if (@available(iOS 12.0, *)) {
  options = options | UNAuthorizationOptionProvisional;
}
[center requestAuthorizationWithOptions:options
                      completionHandler:^(BOOL granted, NSError *_Nullable error) {
                        NSLog(@"Notification authorization, granted: %d, "
                              @"error: %@)",
                              granted, error);
}];

ステップ 3.2:Braze にプッシュトークンを登録する

APNの登録が完了したら、結果のdeviceToken をBrazeに渡し、ユーザーのプッシュ通知を有効にする。

アプリの application(_:didRegisterForRemoteNotificationsWithDeviceToken:) メソッドに次のコードを追加します。

1
AppDelegate.braze?.notifications.register(deviceToken: deviceToken)

アプリの application:didRegisterForRemoteNotificationsWithDeviceToken: メソッドに次のコードを追加します。

1
[AppDelegate.braze.notifications registerDeviceToken:deviceToken];

ステップ3.3:プッシュ処理を有効にする

次に、受信したプッシュ通知をBrazeに渡す。このステップは、プッシュ分析とリンク処理のロギングに必要である。アプリケーションのメインスレッドですべてのプッシュ統合コードを呼び出すようにしてください。

デフォルトのプッシュ処理

ブレーズのデフォルトのプッシュ処理を有効にするには、アプリのapplication(_:didReceiveRemoteNotification:fetchCompletionHandler:) メソッドに次のコードを追加します。

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleBackgroundNotification(
  userInfo: userInfo,
  fetchCompletionHandler: completionHandler
) {
  return
}
completionHandler(.noData)

次に、アプリの userNotificationCenter(_:didReceive:withCompletionHandler:) メソッドに以下を追加します。

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleUserNotification(
  response: response,
  withCompletionHandler: completionHandler
) {
  return
}
completionHandler()

ブレーズのデフォルトのプッシュ処理を有効にするには、以下のコードをアプリケーションのapplication:didReceiveRemoteNotification:fetchCompletionHandler: メソッドに追加します。

1
2
3
4
5
6
7
BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleBackgroundNotificationWithUserInfo:userInfo
                                                                                                       fetchCompletionHandler:completionHandler];
if (processedByBraze) {
  return;
}

completionHandler(UIBackgroundFetchResultNoData);

次に、アプリの (void)userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: メソッドに次のコードを追加します。

1
2
3
4
5
6
7
BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleUserNotificationWithResponse:response
                                                                                                  withCompletionHandler:completionHandler];
if (processedByBraze) {
  return;
}

completionHandler();
フォアグラウンドでのプッシュ通知処理

フォアグラウンドのプッシュ通知を有効にし、受信時に Braze がそれを認識できるようにするには、UNUserNotificationCenter.userNotificationCenter(_:willPresent:withCompletionHandler:) を実装します。ユーザーがフォアグラウンド通知をタップすると、userNotificationCenter(_:didReceive:withCompletionHandler:) プッシュデリゲートが呼び出され、Brazeはプッシュクリックイベントを記録する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func userNotificationCenter(
  _ center: UNUserNotificationCenter,
  willPresent notification: UNNotification,
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions
) -> Void) {
  if let braze = AppDelegate.braze {
    // Forward notification payload to Braze for processing.
    braze.notifications.handleForegroundNotification(notification: notification)
  }

  // Configure application's foreground notification display options.
  if #available(iOS 14.0, *) {
    completionHandler([.list, .banner])
  } else {
    completionHandler([.alert])
  }
}

フォアグラウンドのプッシュ通知を有効にし、受信時に Braze がそれを認識できるようにするには、userNotificationCenter:willPresentNotification:withCompletionHandler: を実装します。ユーザーがフォアグラウンド通知をタップすると、userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: プッシュデリゲートが呼び出され、Brazeはプッシュクリックイベントを記録する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
  if (AppDelegate.braze != nil) {
    // Forward notification payload to Braze for processing.
    [AppDelegate.braze.notifications handleForegroundNotificationWithNotification:notification];
  }

  // Configure application's foreground notification display options.
  if (@available(iOS 14.0, *)) {
    completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
  } else {
    completionHandler(UNNotificationPresentationOptionAlert);
  }
}

テスト通知

コマンドラインからアプリ内通知とプッシュ通知をテストする場合は、CURL とメッセージング API を介してターミナルから単一の通知を送信できます。次のフィールドをテストケースの正しい値に置き換える必要があります。

  • YOUR_API_KEY - [設定] > [API キー] で利用できます。
  • YOUR_EXTERNAL_USER_ID - [ユーザーの検索] ページで使用できます。詳しくはユーザーIDの割り当てを参照のこと。
  • YOUR_KEY1 (省略可能)
  • YOUR_VALUE1 (省略可能)

以下の例では、US-01 インスタンスを使用している。このインスタンスを使用していない場合は、APIドキュメントを参照して、どのエンドポイントにリクエストを行うかを確認すること。

1
2
3
4
5
6
7
8
9
10
11
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {YOUR_API_KEY}" -d '{
  "external_user_ids":["YOUR_EXTERNAL_USER_ID"],
  "messages": {
    "apple_push": {
      "alert":"Test push",
      "extra": {
        "YOUR_KEY1":"YOUR_VALUE1"
      }
    }
  }
}' https://rest.iad-01.braze.com/messages/send

プッシュ通知更新を購読する

Brazeが処理するプッシュ通知ペイロードにアクセスするには Braze.Notifications.subscribeToUpdates(payloadTypes:_:)メソッドを使う。

payloadTypes パラメーターを使用して、プッシュ開封イベント、プッシュ受信イベント、またはその両方を含む通知を購読するかどうかを指定できます。

1
2
3
4
5
6
// This subscription is maintained through a Braze cancellable, which will observe for changes until the subscription is cancelled.
// You must keep a strong reference to the cancellable to keep the subscription active.
// The subscription is canceled either when the cancellable is deinitialized or when you call its `.cancel()` method.
let cancellable = AppDelegate.braze?.notifications.subscribeToUpdates(payloadTypes: [.open, .received]) { payload in
  print("Braze processed notification with title '\(payload.title)' and body '\(payload.body)'")
}
1
2
3
4
5
NSInteger filtersValue = BRZNotificationsPayloadTypeFilter.opened.rawValue | BRZNotificationsPayloadTypeFilter.received.rawValue;
BRZNotificationsPayloadTypeFilter *filters = [[BRZNotificationsPayloadTypeFilter alloc] initWithRawValue: filtersValue];
BRZCancellable *cancellable = [notifications subscribeToUpdatesWithPayloadTypes:filters update:^(BRZNotificationsPayload * _Nonnull payload) {
  NSLog(@"Braze processed notification with title '%@' and body '%@'", payload.title, payload.body);
}];

プッシュプライマー

プッシュプライマーキャンペーンでは、アプリのデバイスでプッシュ通知を有効にするようにユーザーに促します。これは、ノーコードプッシュプライマーを使用して、SDK のカスタマイズなしで行うことができます。

動的APN ゲートウェイ管理

Dynamic Apple Push Notification Service (APNs) ゲートウェイ管理により、正しいAPNs 環境を自動的に検出することで、iOS プッシュ通知の信頼性と効率が向上します。これまでは、プッシュ通知用にAPNs 環境(開発またはプロダクション) を手動で選択していましたが、ゲートウェイ設定の誤り、配信の失敗、BadDeviceToken エラーが発生することがありました。

動的APN ゲートウェイ管理では、次のようになります。

  • 信頼性の向上:通知は常に正しいAPN環境に配信されるため、配信の失敗が減少します。
  • 簡易設定:APNs ゲートウェイ設定を手動で管理する必要がなくなりました。
  • エラー耐性:無効または欠落したゲートウェイ値は正常に処理され、中断されないサービスを提供します。

前提条件

Braze は、次のSDK バージョン要件を備えたiOS でのプッシュ通知のダイナミックAPNs ゲートウェイ管理をサポートしています。

CDI の仕組み

iOS アプリがBraze Swift SDK と統合すると、aps-environment を含むデバイス関連のデータがBraze SDK API に送信されます(利用可能な場合)。apns_gateway の値は、アプリが開発(dev) またはプロダクション(prod) APNs 環境を使用しているかどうかを示します。

また、Braze は、各デバイスについて報告されたゲートウェイ値も格納します。新しい有効なゲートウェイ値を受信すると、Braze は保存された値を自動的に更新します。

Braze がプッシュ通知を送信すると、次のようになります。

  • デバイスに有効なゲートウェイ値(dev またはprod) が格納されている場合、Braze はそれを使用して正しいAPN 環境を判断します。
  • ゲートウェイ値が保存されていない場合、Braze はデフォルトでApp Settings ページで設定されたAPNs 環境に設定されます。

よくある質問

なぜこの機能が導入されたのか?

動的APN ゲートウェイ管理では、正しい環境が自動的に選択されます。以前は、APNs ゲートウェイを手動で設定する必要がありました。これにより、BadDeviceToken エラー、トークンの無効化、および潜在的なAPNs レートリミットの問題が発生する可能性がありました。

この影響は、どのように配信パフォーマンスを押し上げますか?

この機能は、適切なAPN環境に常にプッシュトークンをルーティングし、誤設定されたゲートウェイに起因する障害を回避することで、配信レートを向上させます。

この機能を無効にできますか?

Dynamic APNs Gateway Management はデフォルトでオンになっており、信頼性の向上を提供します。手動ゲートウェイ選択が必要な特定のユースケースがある場合は、Braze Support までお問い合わせください。

Prerequisites

Before you can use this feature, you’ll need to integrate the Web Braze SDK.

Push protocols

Web push notifications are implemented using the W3C push standard, which most major browsers support. For more information on specific push protocol standards and browser support, you can review resources from Apple Mozilla and Microsoft.

Setting up push notifications

Step 1: Configure your service worker

In your project’s service-worker.js file, add the following snippet and set the manageServiceWorkerExternally initialization option to true when initializing the Web SDK.

Step 2: Register the browser

To immediately request push permissions from a user so their browser can receive push notifications, call braze.requestPushPermission(). To test if push is supported in their browser first, call braze.isPushSupported().

You can also send a soft push prompt to the user before requesting push permission to show your own push-related UI.

Step 3: Disable skipWaiting (optional)

The Braze service worker file will automatically call skipWaiting upon install. If you’d like to disable this functionality, add the following code to your service worker file, after importing Braze:

Unsubscribing a user

To unsubscribe a user, call braze.unregisterPush().

Alternate domains

To integrate web push, your domain must be secure, which generally means https, localhost, and other exceptions as defined in the W3C push standard. You’ll also need to be able to register a Service Worker at the root of your domain, or at least be able to control the HTTP headers for that file. This article covers how to integrate Braze Web Push on an alternate domain.

Use cases

If you can’t meet all of the criteria outlined in the W3C push standard, you can use this method to add a push prompt dialog to your website instead. This can be helpful if you want to let your users opt-in from an http website or a browser extension popup that’s preventing your push prompt from displaying.

Considerations

Keep in mind, like many workarounds on the web, browsers continually evolve, and this method may not be viable in the future. Before continuing, ensure that:

  • You own a separate secure domain (https://) and permissions to register a Service Worker on that domain.
  • Users are logged in to your website which ensures push tokens are match to the correct profile.

Setting up an alternate push domain

To make the following example clear, we’ll use use http://insecure.com and https://secure.com as our two domains with the goal of getting visitors to register for push on http://insecure.com. This example could also be applied to a chrome-extension:// scheme for a browser extension’s popup page.

Step 1: Initiate prompting flow

On insecure.com, open a new window to your secure domain using a URL parameter to pass the currently logged-in user’s Braze external ID.

http://insecure.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<button id="opt-in">Opt-In For Push</button>
<script>
// the same ID you would use with `braze.changeUser`:
const user_id = getUserIdSomehow();
// pass the user ID into the secure domain URL:
const secure_url = `https://secure.com/push-registration.html?external_id=${user_id}`;

// when the user takes some action, open the secure URL in a new window
document.getElementById("opt-in").onclick = function(){
    if (!window.open(secure_url, 'Opt-In to Push', 'height=500,width=600,left=150,top=150')) {
        window.alert('The popup was blocked by your browser');
    } else {
        // user is shown a popup window
        // and you can now prompt for push in this window
    }
}
</script>

Step 2: Register for push

At this point, secure.com will open a popup window in which you can initialize the Braze Web SDK for the same user ID and request the user’s permission for Web push.

https://secure.com/push-registration.html

Step 3: Communicate between domains (optional)

Now that users can opt-in from this workflow originating on insecure.com, you may want to modify your site based on if the user is already opted-in or not. There’s no point in asking the user to register for push if they already are.

You can use iFrames and the postMessage API to communicate between your two domains.

insecure.com

On our insecure.com domain, we will ask the secure domain (where push is actually registered) for information on the current user’s push registration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- Create an iframe to the secure domain and run getPushStatus onload-->
<iframe id="push-status" src="https://secure.com/push-status.html" onload="getPushStatus()" style="display:none;"></iframe>

<script>
function getPushStatus(event){
    // send a message to the iframe asking for push status
    event.target.contentWindow.postMessage({type: 'get_push_status'}, 'https://secure.com');
    // listen for a response from the iframe's domain
    window.addEventListener("message", (event) => {
        if (event.origin === "http://insecure.com" && event.data.type === 'set_push_status') {
            // update the page based on the push permission we're told
            window.alert(`Is user registered for push? ${event.data.isPushPermissionGranted}`);
        }
    }   
}
</script>

secure.com/push-status.html

Frequently Asked Questions (FAQ)

Service workers

What if I can’t register a service worker in the root directory?

By default, a service worker can only be used within the same directory it is registered in. For example, if your service worker file exists in /assets/service-worker.js, it would only be possible to register it within example.com/assets/* or a subdirectory of the assets folder, but not on your homepage (example.com/). For this reason, it is recommended to host and register the service worker in the root directory (such as https://example.com/service-worker.js).

If you cannot register a service worker in your root domain, an alternative approach is to use the Service-Worker-Allowed HTTP header when serving your service worker file. By configuring your server to return Service-Worker-Allowed: / in the response for the service worker, this will instruct the browser to broaden the scope and allow it to be used from within a different directory.

Can I create a service worker using a Tag Manager?

No, service workers must be hosted on your website’s server and can’t be loaded via Tag Manager.

Site security

Is HTTPS required?

Yes. Web standards require that the domain requesting push notification permission be secure.

When is a site considered “secure”?

A site is considered secure if it matches one of the following secure-origin patterns. Braze Web push notifications are built on this open standard, so man-in-the-middle attacks are prevented.

  • (https, , *)
  • (wss, *, *)
  • (, localhost, )
  • (, .localhost, *)
  • (, 127/8, )
  • (, ::1/128, *)
  • (file, *, —)
  • (chrome-extension, *, —)

What if a secure site is not available?

While industry best practice is to make your whole site secure, customers who cannot secure their site domain can work around the requirement by using a secure modal. Read more in our guide to using Alternate push domain or view a working demo.

About push notifications for Android TV

While not a native feature, Android TV push integration is made possible by leveraging the Braze Android SDK and Firebase Cloud Messaging to register a push token for Android TV. It is, however, necessary to build a UI to display the notification payload after it is received.

Prerequisites

To use this feature, you’ll need to complete the following:

Setting up push notifications

To set up push notifications for Android TV:

  1. Create a custom view in your app to display your notifications.
  2. Create a custom notification factory. This will override the default SDK behavior and allow you to manually display the notifications. By returning null, this will prevent the SDK from processing and will require custom code to display the notification. After these steps have been completed, you can start sending push to Android TV!

  3. (Optional) To track click analytics effectively, set up click analytics tracking. This can be achieved by creating a push callback to listen for Braze push opened and received intents.

Testing Android TV push notifications

To test if your push implementation is successful, send a notification from the Braze dashboard as you would normally for an Android device.

  • If the application is closed: The push message will display a toast notification on the screen.
  • If the application is open: You have the opportunity to display the message in your own hosted UI. We recommend following the UI styling of our Android Mobile SDK in-app messages.

Best practices

For marketers using Braze, launching a campaign to Android TV will be identical to launching a push to Android mobile apps. To target these devices exclusively, we recommend selecting the Android TV App in segmentation.

The delivered and clicked response returned by FCM will follow the same convention as a mobile Android device; therefore, any errors will be visible in the message activity log.

Prerequisites

Before you can use this feature, you’ll need to integrate the Cordova Braze SDK. After you integrate the SDK, basic push notification functionality is enabled by default. To use rich push notifications and push stories, you’ll need to set them up individually.

Disabling basic push notifications (iOS only)

After you integrate the Braze Cordova SDK for iOS, basic push notification functionality is enabled by default. To disable this functionality in your iOS app, add the following to your config.xml file. For more information, see Optional configurations.

1
2
3
4
<platform name="ios">
    <preference name="com.braze.ios_disable_automatic_push_registration" value="NO" />
    <preference name="com.braze.ios_disable_automatic_push_handling" value="NO" />
</platform>

前提条件

この機能を使う前に、Flutter Braze SDKを統合する必要がある。

Setting up push notifications

Step 1: Complete the initial setup

Step 1.1: Register for push

Register for push using Google’s Firebase Cloud Messaging (FCM) API. For a full walkthrough, refer to the following steps from the Native Android push integration guide:

  1. Add Firebase to your project.
  2. Add Cloud Messaging to your dependencies.
  3. Create a service account.
  4. Generate JSON credentials.
  5. Upload your JSON credentials to Braze.

Step 1.2: Get your Google Sender ID

First, go to Firebase Console, open your project, then select  Settings > Project settings.

The Firebase project with the "Settings" menu open.

Select Cloud Messaging, then under Firebase Cloud Messaging API (V1), copy the Sender ID to your clipboard.

The Firebase project's "Cloud Messaging" page with the "Sender ID" highlighted.

Step 1.3: Update your braze.xml

Add the following to your braze.xml file. Replace FIREBASE_SENDER_ID with the sender ID you copied previously.

1
2
<bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">FIREBASE_SENDER_ID</string>

Step 1.1: Upload APNs certificates

Generate an Apple Push Notification service (APNs) certificate and uploaded it to the Braze dashboard. For a full walkthrough, see Uploading your APNs certificate.

Step 1.2: Add push notification support to your app

Follow the native iOS integration guide.

Step 2: Listen for push notification events (optional)

To listen for push notification events that Braze has detected and handled, call subscribeToPushNotificationEvents() and pass in an argument to execute.

1
2
3
4
5
6
7
8
9
10
// Create stream subscription
StreamSubscription pushEventsStreamSubscription;

pushEventsStreamSubscription = braze.subscribeToPushNotificationEvents((BrazePushEvent pushEvent) {
  print("Push Notification event of type ${pushEvent.payloadType} seen. Title ${pushEvent.title}\n and deeplink ${pushEvent.url}");
  // Handle push notification events
});

// Cancel stream subscription
pushEventsStreamSubscription.cancel();
Push notification event fields

For a full list of push notification fields, refer to the table below:

Step 3: Test displaying push notifications

To test your integration after configuring push notifications in the native layer:

  1. Set an active user in the Flutter application. To do so, initialize your plugin by calling braze.changeUser('your-user-id').
  2. Head to Campaigns and create a new push notification campaign. Choose the platforms that you’d like to test.
  3. Compose your test notification and head over to the Test tab. Add the same user-id as the test user and click Send Test.
  4. You should receive the notification on your device shortly. You may need to check in the Notification Center or update Settings if it doesn’t display.

前提条件

この機能を使用する前に、Android Braze SDKを統合する必要があります。

プッシュ通知の設定

Huawei 製の新しいスマートフォンには、プッシュ配信に使用されるサービス、Huawei Mobile Services (HMS) が、Google の Firebase Cloud Messaging (FCM) の代わりに搭載されています。

ステップ1:Huawei 開発者アカウントに登録する

始める前に、Huawei 開発者アカウントへの登録と設定が必要です。Huawei アカウントで、[My Projects] > [Project Settings] > [App Information] に移動し、App IDApp secret を書き留めます。

ステップ2:Braze ダッシュボードで新しい Huawei アプリを作成する

Braze ダッシュボードで、[設定] ナビゲーションの下にある [アプリ設定] に移動します。

[+ アプリ] をクリックし、名前 (My Huawei App など) を入力し、プラットフォームとして Android を選択します。

新しい Braze アプリを作成したら、プッシュ通知設定を見つけて、プッシュプロバイダーとして Huawei を選択します。次に、Huawei Client SecretHuawei App ID を指定します。

ステップ 3:Huawei メッセージング SDK をアプリに統合する

Huawei は、Huawei Messaging Service をアプリケーションに統合する Android 統合 codelab を提供しています。以下の手順に従って開始してください。

codelab が完了したら、カスタムの Huawei Message Service を作成してプッシュトークンを取得し、メッセージを Braze SDK に転送する必要があります。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CustomPushService extends HmsMessageService {
  @Override
  public void onNewToken(String token) {
    super.onNewToken(token);
    Braze.getInstance(this.getApplicationContext()).setRegisteredPushToken(token);
  }

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    if (BrazeHuaweiPushHandler.handleHmsRemoteMessageData(this.getApplicationContext(), remoteMessage.getDataOfMap())) {
      // Braze has handled the Huawei push notification
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class CustomPushService: HmsMessageService() {
  override fun onNewToken(token: String?) {
    super.onNewToken(token)
    Braze.getInstance(applicationContext).setRegisteredPushToken(token!!)
  }

  override fun onMessageReceived(hmsRemoteMessage: RemoteMessage?) {
    super.onMessageReceived(hmsRemoteMessage)
    if (BrazeHuaweiPushHandler.handleHmsRemoteMessageData(applicationContext, hmsRemoteMessage?.dataOfMap)) {
      // Braze has handled the Huawei push notification
    }
  }
}

カスタムプッシュサービスを追加した後、AndroidManifest.xml に以下を追加します。

1
2
3
4
5
6
7
<service
  android:name="package.of.your.CustomPushService"
  android:exported="false">
  <intent-filter>
    <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
  </intent-filter>
</service>

ステップ4:プッシュ通知のテスト(オプション)

ここまでで、Braze ダッシュボードに新しい Huawei Android アプリを作成し、Huawei 開発者の認証情報を使用して設定し、Braze および Huawei SDK をアプリに統合しました。

次に、Braze で新しいプッシュキャンペーンをテストすることで、統合をテストします。

ステップ4.1:新しいプッシュ通知キャンペーンを作成する

[キャンペーン] ページで、新しいキャンペーンを作成し、メッセージタイプとして [プッシュ通知] を選択します。

キャンペーンに名前を付けたら、プッシュプラットフォームとして [Android プッシュ通知] を選択します。

使用可能なプッシュプラットフォームを表示するキャンペーン登録コンポーザ。

次に、タイトルとメッセージを付けてプッシュキャンペーンを作成します。

ステップ4.2:テストプッシュを送信する

[Test] タブで、changeUser(USER_ID_STRING) method を使ってアプリに設定したユーザーIDを入力し、[Send Test] をクリックしてテストプッシュを送信する。

キャンペーン作成コンポーザーのテストタブを見ると、ユーザーIDを入力し、「個人ユーザーを追加」フィールドに入力することで、自分自身にテストメッセージを送信できることがわかる。

この時点で、Braze から Huawei (HMS) デバイスにテストプッシュ通知が届くはずです。

ステップ4.3:Huawei セグメンテーションのセットアップ(オプション)

Braze ダッシュボードの Huawei アプリは Android プッシュプラットフォーム上に構築されているため、すべての Android ユーザー (Firebase Cloud Messaging および Huawei Mobile Services) にプッシュを送信するか、キャンペーンオーディエンスを特定のアプリにセグメント化するかを柔軟に選択できます。

Huaweiアプリのみにプッシュを送信するには、新しいSegment)を作成し、AppsセクションでHuaweiアプリを選択します。

もちろん、すべての Android プッシュプロバイダーに同じプッシュを送信する場合は、アプリを指定しないことを選択することで、現在のワークスペース内で設定されているすべての Android アプリに送信できます。

Prerequisites

Before you can use this feature, you’ll need to integrate the React Native Braze SDK.

プッシュ通知のセットアップ

ステップ 1: 初期設定を完了する

前提条件

プッシュ通知 のExpo を使用するには、Braze Expo プラグイン を設定する必要があります。

ステップ1.1:app.json ファイルを更新する

次に、Android およびiOS のapp.json を更新します。

  • Android :enableFirebaseCloudMessaging オプションを追加します。
  • iOS:enableBrazeIosPush オプションを追加します。

ステップ1.2:Google の送信者 ID を追加する

まず Firebase Console に移動し、プロジェクトを開いて、[設定] > [プロジェクト設定] を選択します。

[設定] メニューが開いた状態の Firebase プロジェクト。

[Cloud Messaging] 選択し、[Firebase Cloud Messaging API (V1)] の下にある [送信者 ID] をクリップボードにコピーします。

[送信者 ID] が強調表示されている Firebase プロジェクトの「Cloud Messaging」ページ。

次に、プロジェクトのapp.json ファイルを開き、firebaseCloudMessagingSenderId プロパティをクリップボード内の送信者IDに設定する。以下に例を示します。

1
"firebaseCloudMessagingSenderId": "693679403398"

ステップ1.3:Google Services JSONにパスを追加する。

プロジェクトのapp.json ファイルに、google-services.json ファイルへのパスを追加する。このファイルは、お客様の構成で enableFirebaseCloudMessaging: true を設定する場合に必要です。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
  "expo": {
    "android": {
      "googleServicesFile": "PATH_TO_GOOGLE_SERVICES"
    },
    "plugins": [
      [
        "@braze/expo-plugin",
        {
          "androidApiKey": "YOUR-ANDROID-API-KEY",
          "iosApiKey": "YOUR-IOS-API-KEY",
          "enableBrazeIosPush": true,
          "enableFirebaseCloudMessaging": true,
          "firebaseCloudMessagingSenderId": "YOUR-FCM-SENDER-ID",
          "androidHandlePushDeepLinksAutomatically": true
        }
      ],
    ]
  }
}

Expo 通知などの追加のプッシュ通知ライブラリに依存している場合は、ネイティブのセットアップ手順ではなく、これらの設定を使用する必要があることに注意してください。

Braze Expoプラグインを使用していない場合、またはこれらの設定をネイティブで設定する場合は、ネイティブAndroidプッシュインテグレーションガイドを参照してプッシュ用に登録します。

Braze Expo プラグインを使用していない場合、またはこれらの設定をネイティブで設定する場合は、ネイティブiOS プッシュインテグレーションガイドの以下のステップを参照してプッシュに登録します。

ステップ1.1:プッシュ許可の要求

アプリの起動時にプッシュ権限を要求する予定がない場合は、アプリDelegate でrequestAuthorizationWithOptions:completionHandler: コールを省略します。次に、ステップ2にスキップします。そうでない場合は、iOSネイティブ・インテグレーション・ガイドに従うこと。

ステップ1.2 (オプション):プッシュキーを移行する

以前にプッシュキーの管理に expo-notifications を使用していた場合は、アプリケーションのルートフォルダーから expo fetch:ios:certs を実行してください。これにより、プッシュキー (a .p8 ファイル) がダウンロードされ、その後 Braze ダッシュボードにアップロードできるようになります。

ステップ 2:プッシュ通知の許可をリクエストする

iOS および Android 13以降のユーザーにプッシュ通知の許可を要求するには、Braze.requestPushPermission() メソッド (v 1.38.0以降で使用可能) を使用します。Android 12以前の場合、このメソッドは何も実行しません。

このメソッドは、SDK が iOS 上のユーザーにどの権限を要求するかを指定する必須パラメーターを受け取ります。これらのオプションは Android には影響しません。

1
2
3
4
5
6
7
8
const permissionOptions = {
  alert: true,
  sound: true,
  badge: true,
  provisional: false
};

Braze.requestPushPermission(permissionOptions);

ステップ 2.1:プッシュ通知をリッスンする (オプション)

さらに、Braze が受信プッシュ通知を検出して処理したイベントをサブスクライブすることもできます。リスナーキー Braze.Events.PUSH_NOTIFICATION_EVENT を使用します。

1
2
3
4
Braze.addListener(Braze.Events.PUSH_NOTIFICATION_EVENT, data => {
  console.log(`Push Notification event of type ${data.payload_type} seen. Title ${data.title}\n and deeplink ${data.url}`);
  console.log(JSON.stringify(data, undefined, 2));
});
プッシュ通知イベントフィールド

プッシュ通知フィールドの完全なリストについては、以下の表を参照してください。

ステップ3: ディープリンクを有効にする (オプション)

Braze がプッシュ通知をクリックしたときにReact コンポーネント内のディープリンクを処理できるようにするには、まずReact Native Linking ライブラリーで説明されているステップs、または任意のソリューションを実装します。次に、以下の追加ステップs に従ってください。

ディープリンクの詳細については、FAQ の記事を参照してください。

Braze Expo プラグイン を使用している場合は、androidHandlePushDeepLinksAutomaticallytrue に設定することで、プッシュ通知のディープリンクを自動的に処理できます。

代わりに、ディープリンクを手動で処理するには、ネイティブAndroid ドキュメントを参照してください。ディープリンクの追加.

ステップ 3.1:アプリ起動時にプッシュ通知の給与読み込むを保存する

iOS の場合は、AppDelegate の didFinishLaunchingWithOptions メソッドに populateInitialPayloadFromLaunchOptions を追加します。以下に例を示します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"BrazeProject";
  self.initialProps = @{};

  BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:apiKey endpoint:endpoint];
  configuration.triggerMinimumTimeInterval = 1;
  configuration.logger.level = BRZLoggerLevelInfo;
  Braze *braze = [BrazeReactBridge initBraze:configuration];
  AppDelegate.braze = braze;

  [self registerForPushNotifications];
  [[BrazeReactUtils sharedInstance] populateInitialPayloadFromLaunchOptions:launchOptions];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

ステップ 3.2:クローズ状態からのディープリンクの処理

React Native Linking によって処理される基本シナリオに加えて、Braze.getInitialPushPayload メソッドを実装し、url 値を取得して、実行されていないときにアプリを開封するプッシュ通知 s からのディープリンクを考慮します。以下に例を示します。

1
2
3
4
5
6
7
8
9
// Handles deep links when an iOS app is launched from a hard close via push click.
// This edge case is not handled in the React Native Linking library and is provided as a workaround by Braze.
Braze.getInitialPushPayload(pushPayload => {
  if (pushPayload) {
    console.log('Braze.getInitialPushPayload is ' + pushPayload);
    showToast('Initial URL is ' + pushPayload.url);
    handleOpenUrl({ pushPayload.url });
  }
});

ステップ3.3ユニバーサルリンクの有効化(オプション)

ユニバーサルリンクサポートを有効にするには、BrazeReactDelegate.hファイルをiOSディレクトリーに作成し、次のコードスニペットを追加します。

1
2
3
4
5
6
#import <Foundation/Foundation.h>
#import <BrazeKit/BrazeKit-Swift.h>

@interface BrazeReactDelegate: NSObject<BrazeDelegate>

@end

次に、BrazeReactDelegate.m ファイルを作成し、次のコード スニペットを追加します。YOUR_DOMAIN_HOST を実際のドメインに置き換えます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#import "BrazeReactDelegate.h"
#import <UIKit/UIKit.h>

@implementation BrazeReactDelegate

/// This delegate method determines whether to open a given URL.
///
/// Reference the `BRZURLContext` object to get additional details about the URL payload.
- (BOOL)braze:(Braze *)braze shouldOpenURL:(BRZURLContext *)context {
  if ([[context.url.host lowercaseString] isEqualToString:@"YOUR_DOMAIN_HOST"]) {
    // Sample custom handling of universal links
    UIApplication *application = UIApplication.sharedApplication;
    NSUserActivity* userActivity = [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
    userActivity.webpageURL = context.url;
    // Routes to the `continueUserActivity` method, which should be handled in your `AppDelegate`.
    [application.delegate application:application
                 continueUserActivity:userActivity restorationHandler:^(NSArray<id<UIUserActivityRestoring>> * _Nullable restorableObjects) {}];
    return NO;
  }
  // Let Braze handle links otherwise
  return YES;
}

@end

次に、プロジェクトのAppDelegate.m ファイルのdidFinishLaunchingWithOptionsBrazeReactDelegate を作成して登録します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import "BrazeReactUtils.h"
#import "BrazeReactDelegate.h"

@interface AppDelegate ()

// Keep a strong reference to the BrazeDelegate to ensure it is not deallocated.
@property (nonatomic, strong) BrazeReactDelegate *brazeDelegate;

@end

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Other setup code

  self.brazeDelegate = [[BrazeReactDelegate alloc] init];
  braze.delegate = self.brazeDelegate;
}

たとえば、サンプルインテグレーションでは、サンプルアプリhereを参照します。

ステップ 4: 試験プッシュ通知の送信

この時点で、デバイスに通知を送信できるはずです。次のステップに従って、プッシュ統合をテストします。

  1. Braze.changeUserId('your-user-id') メソッドを呼び出して、React Native アプリ ライケーションにアクティブユーザーを設定します。
  2. [キャンペーン] に移動し、新しいプッシュ通知キャンペーンを作成します。テストしたいプラットフォームを選択します。
  3. テスト通知を作成し、[テスト] タブに移動します。テストユーザーと同じ user-id を追加し、[テストを送信] をクリックします。まもなくデバイスに通知が届くはずです。

テスト受信者として独自のユーザID を追加して、プッシュ通知をテストできることを示す Braze プッシュキャンペーン。

Expoプラグインの使用

Expo にプッシュ通知s を設定すると、次のプッシュ通知ビヘイビアを処理できます。ネイティブのAndroid またはiOS レイヤーにコードを書き込む必要はありません。

Androidプッシュを追加FMSに転送する

追加の Firebase Messaging Service (FMS) を使用する場合は、アプリケーションが Braze 以外からプッシュを受信した場合に呼び出すフォールバック FMS を指定できます。以下に例を示します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "expo": {
    "plugins": [
      [
        "@braze/expo-plugin",
        {
          ...
          "androidFirebaseMessagingFallbackServiceEnabled": true,
          "androidFirebaseMessagingFallbackServiceClasspath": "com.company.OurFirebaseMessagingService"
        }
      ]
    ]
  }
}

Expo Application Services でアプリ拡張機能を使用する

Expo Application Services(EAS)を使用していて、enableBrazeIosRichPush またはenableBrazeIosPushStories を有効にしている場合は、プロジェクト内の各アプリ拡張機能に対応するバンドル識別子を宣言する必要がある。EAS でコード署名を管理するためにプロジェクトがどのように構成されているかによって、このステップにアプローチする方法は複数あります。

一つの方法は、Expo のアプリ拡張ドキュメントに従って、app.json ファイルで appExtensions 設定を使用することです。あるいは、Expo のローカル認証情報ドキュメントに従って、credentials.json ファイルで multitarget 設定を行うこともできます。

トラブルシューティング

これらは、Braze React Native SDK およびExpo プラグインとのプッシュ通知統合のための一般的なトラブルシューティングステップです。

プッシュ通知s 動作停止

エキスポプラグインを介したプッシュ通知が機能しなくなった場合:

  1. Braze SDKがまだ”トラッキング セッション s であることを確認します。
  2. wipeData への明示的または暗黙的な呼び出しによってSDKが無効になっていないことを確認します。
  3. Brazeの設定と競合する可能性があるため、Expo または関連ライブラリの最近のアップグレードを確認します。
  4. 最近追加されたプロジェクト依存関係を確認し、既存のプッシュ通知委任メソッドを手動で上書きしているかどうかを確認します。

機器トークンがBrazeに登録されない

デバイストークンがBrazeに登録されない場合は、まずプッシュ通知sが動作を停止しましたを確認します。

問題が解決しない場合は、個別の依存関係がBraze プッシュ通知設定を妨害している可能性があります。削除するか、Braze.registerPushToken を手動で呼び出すことができます。

Prerequisites

Before you can use this feature, you’ll need to integrate the Web Braze SDK. Web SDKのプッシュ通知s を[ に設定する必要もあります。プッシュ通知 s は、Safari v16.4 以降を使用しているiOS およびiPadOS ユーザー s にのみ送信できます。

モバイル用のSafari プッシュの設定

ステップ 1: マニフェスト・ファイルを作成する

ウェブ・アプリケーション・マニフェストは、ユーザーのホーム画面にインストールされたときに、ウェブサイトがどのように表示されるかを制御するJSONファイルである。

例えば、App Switcherが使用する背景のテーマカラーやアイコン、ネイティブアプリのようにフルスクリーンでレンダリングするかどうか、アプリをランドスケープモードで開くかポートレートモードで開くかなどを設定できる。

ウェブサイトのルート・ディレクトリに、以下の必須フィールドを含む新しいmanifest.json ファイルを作成する。

1
2
3
4
5
6
7
8
9
{
  "name": "your app name",
  "short_name": "your app name",
  "display": "fullscreen",
  "icons": [{
    "src": "favicon.ico",
    "sizes": "128x128",
  }]
}

サポートされるフィールドの全リストはこちらで見ることができる。

ウェブサイトの<head> 要素に、マニフェストファイルがホストされている場所を指す次の<link> タグを追加する。

1
<link rel="manifest" href="/manifest.json" />

ステップ3:サービスワーカーを追加する

Web プッシュ統合ガイドで説明されているように、Web サイトには Braze service-worker ライブラリをインポートするサービスワーカーファイルが必要です。

ステップ4: ホーム画面に追加する

一般的なブラウザ(Safari、Chrome、FireFox、Edge など)はすべて、それ以降のバージョンのWeb プッシュ通知に対応しています。iOS またはiPadOS でプッシュ権限をリクエストするには、Share To > ホーム画面に追加を選択して、Web サイトをユーザーのホーム画面に追加する必要があります。ホーム画面に追加は、ユーザーがWeb サイトをブックマークし、貴重なホーム画面の不動産にあなたのアイコンを追加します。

ウェブサイトをブックマークし、ホーム画面に保存するためのオプションを示すiPhone

ステップ5: ネイティブのプッシュプロンプトを表示する

アプリがホーム画面に追加された後、ユーザーがアクションを実行するとき(ボタンをクリックするなど)にプッシュ権限をリクエストできるようになりました。これを行うには、requestPushPermission メソッドを使用するか、コードなしのプッシュプライマーのアプリ内メッセージを使用します。

通知を「許可する」か「許可しない」かを尋ねるプッシュプロンプト

以下に例を示します。

1
2
3
4
5
6
7
8
9
import { requestPushPermission } from "@braze/web-sdk";

button.onclick = function(){
    requestPushPermission(() => {
        console.log(`User accepted push prompt`);
    }, (temporary) => {
        console.log(`User ${temporary ? "temporarily dismissed" : "permanently denied"} push prompt`);
    });
};

次のステップ:

次に、自分自身にテスト・メッセージを送って、統合を検証する。統合が完了したら、プッシュオプトイン率を最適化するために、コードなしのプッシュプライマーメッセージを使用することができる。

前提条件

この機能を使用する前に、Unity Braze SDKを統合する必要があります。

Setting up push notification

Step 1: Set up the platform

Step 1.1: Enable Firebase

To get started, follow the Firebase Unity setup documentation.

Step 1.2: Set your Firebase credentials

You need to input your Firebase Server Key and Sender ID into the Braze dashboard. To do this, log in to the Firebase Developers Console and select your Firebase project. Next, select Cloud Messaging under Settings and copy the Server Key and Sender ID:

In Braze, select your Android app on the App Settings page under Manage Settings. Next, enter your Firebase Server Key in the Firebase Cloud Messaging Server Key field and Firebase Sender ID in the Firebase Cloud Messaging Sender ID field.

Step 1.1: Verify integration method

Braze provides a native Unity solution for automating iOS push integrations. If you you’d like to set up and manage your integration manually instead, see Swift: Push Notifications.

Otherwise, continue to the next step.

Step 1.1: Enable ADM

  1. Create an account with the Amazon Apps & Games Developer Portal if you have not already done so.
  2. Obtain OAuth credentials (Client ID and Client Secret) and an ADM API key.
  3. Enable Automatic ADM Registration Enabled in the Unity Braze Configuration window.
    • Alternatively, you may add the following line to your res/values/braze.xml file to enable ADM registration:
1
  <bool name="com_braze_push_adm_messaging_registration_enabled">true</bool>

Step 2: Configure push notifications

Step 2.1: Configure push settings

The Braze SDK can automatically handle push registration with the Firebase Cloud Messaging Servers to have devices receive push notifications. In Unity, enable Automate Unity Android Integration, then configure the following Push Notification settings.

Step 2.1: Upload your APNs token

Before you can send an iOS push notification using Braze, you need to upload your .p8 push notification file, as described in Apple’s developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID. You’ll also need to specify whether to send notifications to your app’s development or production environment, which is defined by its provisioning profile.
  8. When you’re finished, select Save.

Step 2.2: Enable automatic push

Open the Braze Configuration Settings in the Unity Editor by navigating to Braze > Braze Configuration.

Check Integrate Push With Braze to automatically register users for push notifications, pass push tokens to Braze, track analytics for push opens, and take advantage of our default push notification handling.

Step 2.3: Enable background push (optional)

Check Enable Background Push if you want to enable background mode for push notifications. This allows the system to wake your application from the suspended state when a push notification arrives, enabling your application to download content in response to push notifications. Checking this option is required for our uninstall tracking functionality.

The Unity editor shows the Braze configuration options. In this editor, the "Automate Unity iOS integration", "Integrate push with braze", and "Enable background push" are enabled.

Step 2.4: Disable automatic registration (optional)

Users who have not yet opted-in to push notifications will automatically be authorized for push upon opening your application. To disable this feature and manually register users for push, check Disable Automatic Push Registration.

  • If Disable Provisional Authorization is not checked on iOS 12 or later, the user will be provisionally (silently) authorized to receive quiet push. If checked, the user will be shown the native push prompt.
  • If you need to configure exactly when the prompt is shown at runtime, disable automatic registration from the Braze configuration editor and use AppboyBinding.PromptUserForPushPermissions() instead.

The Unity editor shows the Braze configuration options. In this editor, the "Automate Unity iOS integration", "integrate push with braze", and "disable automatic push registration" are enabled.

Step 2.1: Update AndroidManifest.xml

If your app does not have an AndroidManifest.xml, you can use the following as a template. Otherwise, if you already have an AndroidManifest.xml, ensure that any of the following missing sections are added to your existing AndroidManifest.xml.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="REPLACE_WITH_YOUR_PACKAGE_NAME">

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <permission
    android:name="REPLACE_WITH_YOUR_PACKAGE_NAME.permission.RECEIVE_ADM_MESSAGE"
    android:protectionLevel="signature" />
  <uses-permission android:name="REPLACE_WITH_YOUR_PACKAGE_NAME.permission.RECEIVE_ADM_MESSAGE" />
  <uses-permission android:name="com.amazon.device.messaging.permission.RECEIVE" />

  <application android:icon="@drawable/app_icon" 
               android:label="@string/app_name">

    <!-- Calls the necessary Braze methods to ensure that analytics are collected and that push notifications are properly forwarded to the Unity application. -->
    <activity android:name="com.braze.unity.BrazeUnityPlayerActivity" 
      android:label="@string/app_name" 
      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" 
      android:screenOrientation="sensor">
      <meta-data android:name="android.app.lib_name" android:value="unity" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

    <receiver android:name="com.braze.push.BrazeAmazonDeviceMessagingReceiver" android:permission="com.amazon.device.messaging.permission.SEND">
      <intent-filter>
          <action android:name="com.amazon.device.messaging.intent.RECEIVE" />
          <action android:name="com.amazon.device.messaging.intent.REGISTRATION" />
          <category android:name="REPLACE_WITH_YOUR_PACKAGE_NAME" />
      </intent-filter>
    </receiver>
  </application>
</manifest>

Step 2.2: Store your ADM API key

First, generate an ADM API Key for your app, then save the key to a file named api_key.txt and add it in your project’s Assets/ directory.

Next, in your mainTemplate.gradle file, add the following:

1
2
3
4
5
6
7
task copyAmazon(type: Copy) {
    def unityProjectPath = $/file:///**DIR_UNITYPROJECT**/$.replace("\\", "/")
    from unityProjectPath + '/Assets/api_key.txt'
    into new File(projectDir, 'src/main/assets')
}

preBuild.dependsOn(copyAmazon)

Step 2.3: Add ADM Jar

The required ADM Jar file may be placed anywhere in your project according to the Unity JAR documentation.

Step 2.4: Add Client Secret and Client ID to your Braze dashboard

Lastly, you must add the Client Secret and Client ID you obtained in Step 1 to the Braze dashboard’s Manage Settings page.

Step 3: Set push listeners

Step 3.1: Enable push received listener

The push received listener is fired when a user receives a push notification. To send the push payload to Unity, set the name of your game object and push the received listener callback method under the Set Push Received Listener.

Step 3.2: Enable push opened listener

The push opened listener is fired when a user launches the app by clicking on a push notification. To send the push payload to Unity, set the name of your game object and push opened listener callback method under the Set Push Opened Listener.

Step 3.3: Enable push deleted listener

The push deleted listener is fired when a user swipes away or dismisses a push notification. To send the push payload to Unity, set the name of your game object and push deleted listener callback method under the Set Push Deleted Listener.

Push listener example

The following example implements the BrazeCallback game object using a callback method name of PushNotificationReceivedCallback, PushNotificationOpenedCallback, and PushNotificationDeletedCallback respectively.

This implementation example graphic shows the Braze configuration options mentioned in the preceding sections and a C# code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MainMenu : MonoBehaviour {
  void PushNotificationReceivedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationReceivedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification received: " + pushNotification);   
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push received Notification event: " + pushNotification);   
#endif  
  }

  void PushNotificationOpenedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationOpenedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification opened: " + pushNotification);  
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push opened Notification event: " + pushNotification);   
#endif  
  }

  void PushNotificationDeletedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationDeletedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification dismissed: " + pushNotification);  
#endif
  }
}

Step 3.1: Enable push received listener

The push received listener is fired when a user receives a push notification while actively using the application (such as when the app is foregrounded). Set the push received listener in the Braze configuration editor. If you need to configure your game object listener at runtime, use AppboyBinding.ConfigureListener() and specify BrazeUnityMessageType.PUSH_RECEIVED.

The Unity editor shows the Braze configuration options. In this editor, the "Set Push Received Listener" option is expanded, and the "Game Object Name" (AppBoyCallback) and "Callback Method Name" (PushNotificationReceivedCallback) are provided.

Step 3.2: Enable push opened listener

The push opened listener is fired when a user launches the app by clicking on a push notification. To send the push payload to Unity, set the name of your game object and push opened listener callback method under the Set Push Opened Listener option:

The Unity editor shows the Braze configuration options. In this editor, the "Set Push Received Listener" option is expanded, and the "Game Object Name" (AppBoyCallback) and "Callback Method Name" (PushNotificationOpenedCallback) are provided.

If you need to configure your game object listener at runtime, use AppboyBinding.ConfigureListener() and specify BrazeUnityMessageType.PUSH_OPENED.

Push listener example

The following example implements the AppboyCallback game object using a callback method name of PushNotificationReceivedCallback and PushNotificationOpenedCallback, respectively.

This implementation example graphic shows the Braze configuration options mentioned in the preceding sections and a C# code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MainMenu : MonoBehaviour {
  void PushNotificationReceivedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationReceivedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification received: " + pushNotification);   
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push received Notification event: " + pushNotification);   
#endif  
  }

  void PushNotificationOpenedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationOpenedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification opened: " + pushNotification);  
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push opened Notification event: " + pushNotification);   
#endif  
  }
}

By updating your AndroidManifest.xml in the previous step, push listeners were automatically set up when you added the following lines. So, no further setup is required.

1
2
<action android:name="com.amazon.device.messaging.intent.RECEIVE" />
<action android:name="com.amazon.device.messaging.intent.REGISTRATION" />

Optional configurations

Deep linking to in-app resources

Although Braze can handle standard deep links (such as website URLs, Android URIs, etc.) by default, creating custom deep links requires an additional Manifest setup.

For setup guidance, visit Deep Linking to In-App Resources.

Adding Braze push notification icons

To add push icons to your project, create an Android Archive (AAR) plug-in or Android library that contains the icon image files. For steps and information, refer to Unity’s documentation: Android Library Projects and Android Archive plug-ins.

Push token callback

To receive a copy of Braze device tokens from the OS, set a delegate using AppboyBinding.SetPushTokenReceivedFromSystemDelegate().

There are no optional configurations for ADM at this time.

Prerequisites

Before you can use this feature, you’ll need to integrate the Unreal Engine Braze SDK.

プッシュ通知の設定

ステップ1:プロジェクトを設定する

最初に、FirebaseをAndroidプロジェクトに追加します。手順については、GoogleのFirebaseセットアップガイドを参照してください。

Before you can send an iOS push notification using Braze, you need to upload your .p8 push notification file, as described in Apple’s developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID. You’ll also need to specify whether to send notifications to your app’s development or production environment, which is defined by its provisioning profile.
  8. When you’re finished, select Save.

ステップ2:プッシュ通知を有効にする

プロジェクトのengine.ini ファイルに次の行を追加します。YOUR_SEND_ID は必ずFirebase プロジェクト の[送信者ID に置き換えてください。

1
2
3
bEnableFirebaseCloudMessagingSupport=true
bIsFirebaseCloudMessagingRegistrationEnabled=true
FirebaseCloudMessagingSenderIdKey=YOUR_SENDER_ID

BrazeUPLAndroid.xml と同じディレクトリ内にAndroidCopies という名前の新しいディレクトリを作成し、google-services.json ファイルを追加します。

プロジェクトで、Settings > Project Settings > iOS > Onlineに移動し、Enable Remote Notifications Support完了したら、プロビジョニングでプッシュ機能が有効になっていることを確認します。

オプション構成

大小のアイコンを設定する

小規模かつ大規模な通知アイコンを設定するには:

  1. AndroidCopies/res フォルダ内の適切な描画可能フォルダ(デフォルトではdrawable) にアイコンを追加します。
  2. braze.xmlAndroidCopies/res/values フォルダに追加してアイコンを設定します。非常に基本的なbraze.xml ファイル:
    1
    2
    3
    4
    5
    
     <?xml version="1.0" encoding="utf-8"?>
     <resources>
         <drawable name="com_braze_push_small_notification_icon">@drawable/notification_small_icon</drawable>
         <drawable name="com_braze_push_large_notification_icon">@drawable/notification_large_icon</drawable>
     </resources>
    

リモート起動通知

Unreal Engine バージョン4.25.3 では、UE4 はアプリケーションの初期起動を引き起こすリモート通知を受信するための適切なサポートを欠いています。この通知の受信をサポートするために、2 つのgit パッチ(UE4 用とBraze SDK プラグイン用) を作成しました。

  1. UE4 Engine Source ディレクトリで、git パッチUE4_Engine-Cache-Launch-Remote-Notification.patch を適用します。
  2. Braze Unreal SDK ディレクトリで、git パッチBraze_SDK-Read-Cached-Remote-Launch-Notification.patch を適用します。

前提条件

この機能を使用する前に、Xamarin Braze SDKを統合する必要があります。

Setting up push notifications

To integrate push notifications for Xamarin, you’ll need to complete the steps for native Android push notifications. The following steps are only a summary. For a full walkthrough, see the native push notification guide.

Step 1: Update your project

  1. Add Firebase to your Android project.
  2. Add the Cloud Messaging library to your Android project’s build.gradle:
    1
    
      implementation "google.firebase:firebase-messaging:+"
    

Step 2: Create your JSON credentials

  1. In Google Cloud, enable the Firebase Cloud Messaging API.
  2. Select Service Accounts > your project > Create Service Account, then enter a service account name, ID, and description. When you’re finished, select Create and continue.
  3. In the Role field, find and select Firebase Cloud Messaging API Admin from the list of roles.
  4. In Service Accounts, choose your project, then select  Actions > Manage Keys > Add Key > Create new key. Choose JSON, then select Create.

Step 3: Upload your JSON credentials

  1. In Braze, select  Settings > App Settings. Under your Android app’s Push Notification Settings, choose Firebase, then select Upload JSON File and upload the credentials you generated earlier. When you’re finished, select Save.
  2. Enable automatic FCM token registration, by going to Firebase Console. Open your project, then select  Settings > Project settings. Select Cloud Messaging, then under Firebase Cloud Messaging API (V1), copy the number in the Sender ID field.
  3. In your Android Studio project and the following to your braze.xml.
1
2
  <bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
  <string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">FIREBASE_SENDER_ID</string>

Step 1: Complete the initial setup

See the Swift integration instructions for information about setting up your application with push and storing your credentials on our server. Refer to the iOS MAUI sample application for more details.

Step 2: Request push notifications permission

Our Xamarin SDK now supports automatic push set up. Set up push automation and permissions by adding the following code to your Braze instance configuration:

1
2
configuration.Push.Automation = new BRZConfigurationPushAutomation(true);
configuration.Push.Automation.RequestAuthorizationAtLaunch = false;

Refer to the iOS MAUI sample application for more details. For more details, see the Xamarin documentation for Enhanced User Notifications in Xamarin.iOS.

New Stuff!