Exemples de notifications push avancées
Le guide suivant couvre quelques exemples de notifications push avancées pour le SDK de Braze.
Conditions préalables
Avant de pouvoir utiliser cette fonctionnalité, vous devrez intégrer le SDK Android Braze. Vous devrez également configurer les notifications push.
Disposition personnalisée des notifications
Les notifications de Braze sont envoyées sous forme de messages de données, ce qui signifie que votre application aura toujours une chance de répondre et d’effectuer un comportement en conséquence, même en arrière-plan (contrairement aux messages de notification, qui peuvent être traités automatiquement par le système lorsque votre application est en arrière-plan). Ainsi, votre application aura la possibilité de personnaliser l’expérience, par exemple en affichant des éléments d’IU personnalisés dans la notification envoyée à la barre de notification. Bien que l’implémentation de push de cette manière puisse être peu familière à certains, l’une de nos fonctionnalités bien connues chez Braze, Push Stories, est un excellent exemple de l’utilisation de composants de vue personnalisés pour créer une expérience engageante !
Android impose certaines limitations sur les composants pouvant être utilisés pour implémenter des vues personnalisées. Les dispositions de la vue de la notification doivent uniquement contenir des objets de vue compatibles avec le framework RemoteViews.
Vous pouvez utiliser l’interface IBrazeNotificationFactory pour personnaliser l’affichage des notifications push de Braze. En étendant BrazeNotificationFactory, Braze appellera la méthode createNotification() de votre usine avant que la notification ne soit affichée à l’utilisateur. Il transmettra ensuite une charge utile contenant des paires clé-valeur personnalisées envoyées via le tableau de bord de Braze ou l’API REST.
Dans cette section, vous serez le partenaire de Superb Owl, l’animateur d’un nouveau jeu télévisé dans lequel des équipes de sauvetage d’animaux sauvages s’affrontent pour savoir qui peut enregistrer le plus grand nombre de hiboux. Ils cherchent à exploiter les notifications de mise à jour en ligne dans leur application Android, afin d’afficher le statut d’un match en cours et d’effectuer des mises à jour dynamiques de la notification en temps réel.

Étape 1 : Ajouter une mise en page personnalisée
Vous pouvez ajouter une ou plusieurs présentations RemoteView de notification personnalisées à votre projet. Ils permettent de gérer l’affichage des notifications lorsqu’elles sont réduites ou développées. La structure de votre répertoire devrait ressembler à ce qui suit :
1
2
3
4
5
6
.
├── app/
└── res/
└── layout/
├── liveupdate_collapsed.xml
└── liveupdate_expanded.xml
Dans chaque fichier XML, créez une mise en page personnalisée. Superb Owl a créé les mises en page suivantes pour leurs mises en page RemoteView réduites et étendues :
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/notification_title"
style="@style/TextAppearance.Compat.Notification.Title"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
Montrer le code d’exemple
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/team1logo"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center"
android:src="@drawable/team_default1"/>
<TextView
android:id="@+id/team1name"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1.6"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2-4"
android:textColor="#555555"
android:textAlignment="center"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/timeInfo"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/team2logo"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:src="@drawable/team_default2"/>
<TextView
android:id="@+id/team2name"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Étape 2 : Créer une fabrique de notifications personnalisées
Dans votre application, créez un nouveau fichier nommé MyCustomNotificationFactory.kt qui étend BrazeNotificationFactory pour gérer l’affichage des présentations RemoteView personnalisées.
Dans l’exemple suivant, Superb Owl a créé une usine de notification personnalisée pour afficher une mise en page RemoteView pour les matchs en cours. Dans l’ étape suivante, ils créeront une nouvelle méthode appelée getTeamInfo pour mapper les données d’une équipe à l’activité.
Montrer le code d’exemple
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import android.app.Notification
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.braze.models.push.BrazeNotificationPayload
import com.braze.push.BrazeNotificationFactory
import com.braze.push.BrazeNotificationUtils.getOrCreateNotificationChannelId
import com.braze.support.BrazeLogger.brazelog
class MyCustomNotificationFactory : BrazeNotificationFactory() {
override fun createNotification(payload: BrazeNotificationPayload): Notification? {
if (payload.extras.containsKey("live_update")) {
val kvp = payload.extras
val notificationChannelId = getOrCreateNotificationChannelId(payload)
val context = payload.context
if (context == null) {
brazelog { "BrazeNotificationPayload has null context. Not creating notification" }
return null
}
val team1 = kvp["team1"]
val team2 = kvp["team2"]
val score1 = kvp["score1"]
val score2 = kvp["score2"]
val time = kvp["time"]
val quarter = kvp["quarter"]
// Superb Owl will define the 'getTeamInfo' method in the next step.
val (team1name, team1icon) = getTeamInfo(team1)
val (team2name, team2icon) = getTeamInfo(team2)
// Get the layouts to use in the custom notification.
val notificationLayoutCollapsed = RemoteViews(BuildConfig.APPLICATION_ID, R.layout.liveupdate_collapsed)
val notificationLayoutExpanded = RemoteViews(BuildConfig.APPLICATION_ID, R.layout.liveupdate_expanded)
// Very simple notification for the small layout
notificationLayoutCollapsed.setTextViewText(
R.id.notification_title,
"$team1 $score1 - $score2 $team2\n$time $quarter"
)
notificationLayoutExpanded.setTextViewText(R.id.score, "$score1 - $score2")
notificationLayoutExpanded.setTextViewText(R.id.team1name, team1name)
notificationLayoutExpanded.setTextViewText(R.id.team2name, team2name)
notificationLayoutExpanded.setTextViewText(R.id.timeInfo, "$time - $quarter")
notificationLayoutExpanded.setImageViewResource(R.id.team1logo, team1icon)
notificationLayoutExpanded.setImageViewResource(R.id.team2logo, team2icon)
val customNotification = NotificationCompat.Builder(context, notificationChannelId)
.setSmallIcon(R.drawable.notification_small_icon)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.build()
return customNotification
} else {
// Use the BrazeNotificationFactory for all other notifications
return super.createNotification(payload)
}
}
}
Étape 3 : Mappage de données personnalisées
Dans MyCustomNotificationFactory.kt, créez une nouvelle méthode pour traiter les données lorsque des mises à jour en direct sont affichées.
Superb Owl a créé la méthode suivante pour mapper le nom et le logo de chaque équipe aux lignes/en production/instantanées étendues :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CustomNotificationFactory : BrazeNotificationFactory() {
override fun createNotification(payload: BrazeNotificationPayload): Notification? {
// Your existing code
return super.createNotification(payload)
}
// Your new method
private fun getTeamInfo(team: String?): Pair<String, Int> {
return when (team) {
"WBF" -> Pair("Wild Bird Fund", R.drawable.team_wbf)
"OWL" -> Pair("Owl Rehab", R.drawable.team_owl)
else -> Pair("Unknown", R.drawable.notification_small_icon)
}
}
}
Étape 4 : Définir la fabrique de notifications personnalisée
Dans votre classe d’application, utilisez customBrazeNotificationFactorypour définir votre fabrique de notifications personnalisée.
1
2
3
4
5
6
7
8
9
10
import com.braze.Braze
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// Tell Braze to use your custom factory for notifications
Braze.customBrazeNotificationFactory = MyCustomNotificationFactory()
}
}
Étape 5 : Envoyer l’activité
Vous pouvez utiliser le point d’arrivée de l’API /messages/send REST API endpoint pour envoyer une notification push à l’appareil Android d’un utilisateur.
Exemple de commande curl
Superb Owl a envoyé sa requête en utilisant la commande curl suivante :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
curl -X POST "https://BRAZE_REST_ENDPOINT/messages/send" \
-H "Authorization: Bearer {REST_API_KEY}" \
-H "Content-Type: application/json" \
--data '{
"external_user_ids": ["USER_ID"],
"messages": {
"android_push": {
"title": "WBF vs OWL",
"alert": "2 to 4 1:33 Q4",
"extra": {
"live_update": "true",
"team1": "WBF",
"team2": "OWL",
"score1": "2",
"score2": "4",
"time": "1:33",
"quarter": "Q4"
},
"notification_id": "ASSIGNED_NOTIFICATION_ID"
}
}
}'
Bien que les commandes curl soient utiles pour les tests, nous recommandons de gérer cet appel dans votre backend où vous gérez déjà vos activités iOS Live.
Paramètres de demande
| Clé | Description |
|---|---|
REST_API_KEY |
Une clé API Braze REST avec des autorisations messages.send. Cette clé peut être créée dans le tableau de bord de Braze depuis Paramètres > Clés d’API. |
BRAZE_REST_ENDPOINT |
L’URL de votre endpoint REST. Votre endpoint dépendra de l’URL de Braze pour votre instance. |
USER_ID |
L’ID de l’utilisateur auquel vous envoyez la notification. |
messages.android_push.title |
Titre du message. Par défaut, elle n’est pas utilisée pour les notifications en ligne/en production/instantanée de la fabrique de notifications personnalisée, mais elle peut être utilisée comme solution de repli. |
messages.android_push.alert |
Le corps du message. Par défaut, elle n’est pas utilisée pour les notifications en ligne/en production/instantanée de la fabrique de notifications personnalisée, mais elle peut être utilisée comme solution de repli. |
messages.extra |
Paires clé-valeur que la fabrique de notifications personnalisée utilise pour les notifications en ligne/en production/instantanée. Vous pouvez attribuer n’importe quelle chaîne de caractères à cette valeur. Toutefois, dans l’exemple ci-dessus, live_updates est utilisé pour déterminer s’il s’agit d’une notification push par défaut ou en direct. |
ASSIGNED_NOTIFICATION_ID |
L’ID de notification que vous souhaitez attribuer à la notification en ligne/instantanée de l’utilisateur choisi. L’ID doit être unique pour ce jeu et doit être utilisé pour mettre à jour la notification existante ultérieurement. |
Étape 6 : Mettre à jour l’activité
Pour mettre à jour la notification RemoteView existante avec de nouvelles données, modifiez les paires clé-valeur pertinentes attribuées à messages.extra, puis utilisez le même notification_id et appelez à nouveau le point de terminaison /messages/send.
Notifications push personnalisées
Les notifications push peuvent afficher des informations spécifiques à l’utilisateur dans une hiérarchie de vue personnalisée. Dans l’exemple suivant, un déclencheur API est utilisé pour envoyer une notification push personnalisée à un utilisateur afin qu’il puisse suivre sa progression après avoir accompli une tâche spécifique dans l’application.

Pour configurer un push personnalisé dans le tableau de bord, enregistrez la catégorie spécifique que vous souhaitez voir s’afficher, puis définissez tous les attributs utilisateur pertinents que vous souhaitez afficher à l’aide de Liquid.

Conditions préalables
Avant de pouvoir utiliser cette fonctionnalité, vous devrez intégrer le SDK Swift Braze. You’ll also need to set up push notifications.
This implementation guide is centered around a Swift implementation, but Objective-C snippets are provided for those interested.
Notification content app extensions

Notification content app extensions provide you a great option for push notification customization. Notification content app extensions display a custom interface for your app’s notifications when a push notification is expanded.
Push notifications can be expanded in three different ways:
- A long press on the push banner
- Swiping down on the push banner
- Swiping the banner to the left and selecting “View”
These custom views offer smart ways to engage customers by displaying distinct types of content, including interactive notifications, notifications populated with user data, and even push messages that can capture information like phone numbers and email. One of our well-known features at Braze, Push Stories, are a prime example of what a push notification content app extension can look like!
Requirements

- Push notifications successfully integrated in your app
- The following files generated by Xcode based on your coding language:
Swift
NotificationViewController.swiftMainInterface.storyboard
Objective-C
NotificationViewController.hNotificationViewController.mMainInterface.storyboard
Interactive push notification
Push notifications can respond to user actions inside a content app extension. For users running iOS 12 or later, this means you can turn your push notifications into fully interactive messages! This provides an exciting option to introduce interactivity to your promotions and applications. For example, your push notification can include a game for users to play, a spin-to-win wheel for discounts, or a “like” button to save a listing or song.
The following example shows a push notification where users are able to play a match game inside the expanded notification.

Dashboard configuration
To create an interactive push notification, you must set a custom view in your dashboard.
- From the Campaigns page, click Create Campaign to start a new push notification campaign.
- On the Compose tab, toggle on Notification Buttons.
- Enter a custom iOS category in the iOS Notification Category field.
- In the
.plistof your Notification Content Extension Target, set theUNNotificationExtensionCategoryattribute to your custom iOS category. The value given here must match what is set in the Braze dashboard under iOS Notification Category. - Set the
UNNotificationExtensionInteractionEnabledkey totrueto enable user interactions in a push notification.

Personalized push notifications

Push notifications can display user-specific information inside a content extension. This allows you to create user-focused push content, such as adding the option to share your progress across different platforms, show unlocked achievements, or display onboarding checklists. This example shows a push notification displayed to a user after they have completed a specific task in the Braze Learning course. By expanding the notification, the user can see their progress through their learning path. The information provided here is user-specific and can be fired off as a session is completed or a specific user action is taken by leveraging an API trigger.
Dashboard configuration
To create a personalized push notification, you must set a custom view in your dashboard.
- From the Campaigns page, click Create Campaign to start a new push notification campaign.
- On the Compose tab, toggle on Notification Buttons.
- Enter a custom iOS category in the iOS Notification Category field.
- In the Settings tab, create key-value pairs using standard Liquid. Set the appropriate user attributes you want the message to show. These views can be personalized based on specific user attributes of a specific user profile.
- In the
.plistof your Notification Content Extension Target, set theUNNotificationExtensionCategoryattribute to your custom iOS category. The value given here must match what is set in the Braze dashboard under iOS Notification Category.

Handling key-value pairs
The method didReceive is called when the notification content app extension has received a notification. This method can be found within the NotificationViewController. The key-value pairs provided in the dashboard are represented in the code through the use of a userInfo dictionary.
Parsing Key-Value Pairs from Push Notifications
1
2
3
4
5
6
7
8
9
func didReceive(_ notification: UNNotification) {
let userInfo = notification.request.content.userInfo
guard let value = userInfo["YOUR-KEY-VALUE-PAIR"] as? String,
let otherValue = userInfo["YOUR-OTHER-KEY-VALUE-PAIR"] as? String,
else { fatalError("Key-Value Pairs are incorrect.")}
...
}
1
2
3
4
5
6
7
8
9
10
11
- (void)didReceiveNotification:(nonnull UNNotification *)notification {
NSDictionary *userInfo = notification.request.content.userInfo;
if (userInfo[@"YOUR-KEY-VALUE-PAIR"] && userInfo[@"YOUR-OTHER-KEY-VALUE-PAIR"]) {
...
} else {
[NSException raise:NSGenericException format:@"Key-Value Pairs are incorrect"];
}
}
Information capture push notification
Push notifications can capture user information inside a content app extension, pushing the limits of what is possible with a push. Requesting user input through push notifications allows you to not only request basic information like name or email, but also prompt users to submit feedback or complete an unfinished user profile.
For more information, see Logging push notification data.
In the following flow, the custom view is able to respond to state changes. Those state change components are represented in each image.
- User receives a push notification.
- Push is opened. After expanded, the push prompts the user for information. In this example, the user’s email address is requested, but you could request any sort of information.
- Information is provided, and if in the expected format, the registration button is shown.
- Confirmation view is displayed, and push gets dismissed.

Dashboard configuration
To create an information capture push notification, you must set a custom view in your dashboard.
- From the Campaigns page, click Create Campaign to start a new push notification campaign.
- On the Compose tab, toggle on Notification Buttons.
- Enter a custom iOS category in the iOS Notification Category field.
- In the Settings tab, create key-value pairs using standard Liquid. Set the appropriate user attributes you want the message to show.
- In the
.plistof your Notification Content Extension Target, set theUNNotificationExtensionCategoryattribute to your custom iOS category. The value given here must match what is set in the Braze dashboard under iOS Notification Category.
As seen in the example, you may also include an image in your push notification. To do this, you must integrate rich notifications, set the notification style in your campaign to Rich Notification, and include a rich push image.

Handling button actions
Each action button is uniquely identified. The code checks if your response identifier is equal to the actionIndentifier, and if so, knows that the user clicked the action button.
Handling Push Notification Action Button Responses
1
2
3
4
5
6
7
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
if response.actionIdentifier == "YOUR-REGISTER-IDENTIFIER" {
// do something
} else {
// do something else
}
}
1
2
3
4
5
6
7
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion {
if ([response.actionIdentifier isEqualToString:@"YOUR-REGISTER-IDENTIFIER"]) {
completion(UNNotificationContentExtensionResponseOptionDismiss);
} else {
completion(UNNotificationContentExtensionResponseOptionDoNotDismiss);
}
}
Dismissing pushes
Push notifications can be automatically dismissed from an action button press. There are three pre-built push dismissal options that we recommend:
completion(.dismiss)- Dismisses the notificationcompletion(.doNotDismiss)- Notification stays opencompletion(.dismissAndForward)- Push dismisses and the user gets forwarded into the application
Modifier cette page sur GitHub