-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
messaging.dart
293 lines (260 loc) 路 10.5 KB
/
messaging.dart
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// ignore_for_file: require_trailing_commas
// Copyright 2020, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of firebase_messaging;
/// The [FirebaseMessaging] entry point.
///
/// To get a new instance, call [FirebaseMessaging.instance].
class FirebaseMessaging extends FirebasePluginPlatform {
// Cached and lazily loaded instance of [FirebaseMessagingPlatform] to avoid
// creating a [MethodChannelFirebaseMessaging] when not needed or creating an
// instance with the default app before a user specifies an app.
FirebaseMessagingPlatform? _delegatePackingProperty;
static Map<String, FirebaseMessaging> _firebaseMessagingInstances = {};
FirebaseMessagingPlatform get _delegate {
return _delegatePackingProperty ??= FirebaseMessagingPlatform.instanceFor(
app: app, pluginConstants: pluginConstants);
}
/// The [FirebaseApp] for this current [FirebaseMessaging] instance.
FirebaseApp app;
FirebaseMessaging._({required this.app})
: super(app.name, 'plugins.flutter.io/firebase_messaging');
/// Returns an instance using the default [FirebaseApp].
static FirebaseMessaging get instance {
FirebaseApp defaultAppInstance = Firebase.app();
return FirebaseMessaging._instanceFor(app: defaultAppInstance);
}
// Messaging does not yet support multiple Firebase Apps. Default app only.
/// Returns an instance using a specified [FirebaseApp].
factory FirebaseMessaging._instanceFor({required FirebaseApp app}) {
return _firebaseMessagingInstances.putIfAbsent(app.name, () {
final instance = FirebaseMessaging._(app: app);
FirebasePluginPlatform.verify(instance);
return instance;
});
}
/// Returns a Stream that is called when an incoming FCM payload is received whilst
/// the Flutter instance is in the foreground.
///
/// The Stream contains the [RemoteMessage].
///
/// To handle messages whilst the app is in the background or terminated,
/// see [onBackgroundMessage].
static Stream<RemoteMessage> get onMessage =>
FirebaseMessagingPlatform.onMessage.stream;
/// Returns a [Stream] that is called when a user presses a notification message displayed
/// via FCM.
///
/// A Stream event will be sent if the app has opened from a background state
/// (not terminated).
///
/// If your app is opened via a notification whilst the app is terminated,
/// see [getInitialMessage].
static Stream<RemoteMessage> get onMessageOpenedApp =>
FirebaseMessagingPlatform.onMessageOpenedApp.stream;
// ignore: use_setters_to_change_properties
/// Set a message handler function which is called when the app is in the
/// background or terminated.
///
/// This provided handler must be a top-level function and cannot be
/// anonymous otherwise an [ArgumentError] will be thrown.
// ignore: use_setters_to_change_properties
static void onBackgroundMessage(BackgroundMessageHandler handler) {
FirebaseMessagingPlatform.onBackgroundMessage = handler;
}
/// Returns whether messaging auto initialization is enabled or disabled for the device.
bool get isAutoInitEnabled {
return _delegate.isAutoInitEnabled;
}
/// If the application has been opened from a terminated state via a [RemoteMessage]
/// (containing a [Notification]), it will be returned, otherwise it will be `null`.
///
/// Once the [RemoteMessage] has been consumed, it will be removed and further
/// calls to [getInitialMessage] will be `null`.
///
/// This should be used to determine whether specific notification interaction
/// should open the app with a specific purpose (e.g. opening a chat message,
/// specific screen etc).
Future<RemoteMessage?> getInitialMessage() {
return _delegate.getInitialMessage();
}
/// Removes access to an FCM token previously authorized.
///
/// Messages sent by the server to this token will fail.
Future<void> deleteToken() {
return _delegate.deleteToken();
}
/// On iOS/MacOS, it is possible to get the users APNs token.
///
/// This may be required if you want to send messages to your iOS/MacOS devices
/// without using the FCM service.
///
/// On Android & web, this returns `null`.
Future<String?> getAPNSToken() {
return _delegate.getAPNSToken();
}
/// Returns the default FCM token for this device.
///
/// On web, a [vapidKey] is required.
Future<String?> getToken({
String? vapidKey,
}) {
return _delegate.getToken(
vapidKey: vapidKey,
);
}
/// Fires when a new FCM token is generated.
Stream<String> get onTokenRefresh {
return _delegate.onTokenRefresh;
}
Future<bool> isSupported() {
return _delegate.isSupported();
}
/// Returns the current [NotificationSettings].
///
/// To request permissions, call [requestPermission].
Future<NotificationSettings> getNotificationSettings() {
return _delegate.getNotificationSettings();
}
/// Prompts the user for notification permissions.
///
/// - On iOS, a dialog is shown requesting the users permission.
/// - On macOS, a notification will appear asking to grant permission.
/// - On Android, a [NotificationSettings] class will be returned with the
/// value of [NotificationSettings.authorizationStatus] indicating whether
/// the app has notifications enabled or blocked in the system settings.
/// - On Web, a popup requesting the users permission is shown using the native browser API.
///
/// Note that on iOS, if [provisional] is set to `true`, silent notification permissions will be
/// automatically granted. When notifications are delivered to the device, the
/// user will be presented with an option to disable notifications, keep receiving
/// them silently or enable prominent notifications.
Future<NotificationSettings> requestPermission({
/// Request permission to display alerts. Defaults to `true`.
///
/// iOS/macOS only.
bool alert = true,
/// Request permission for Siri to automatically read out notification messages over AirPods.
/// Defaults to `false`.
///
/// iOS only.
bool announcement = false,
/// Request permission to update the application badge. Defaults to `true`.
///
/// iOS/macOS only.
bool badge = true,
/// Request permission to display notifications in a CarPlay environment.
/// Defaults to `false`.
///
/// iOS only.
bool carPlay = false,
/// Request permission for critical alerts. Defaults to `false`.
///
/// Note; your application must explicitly state reasoning for enabling
/// critical alerts during the App Store review process or your may be
/// rejected.
///
/// iOS only.
bool criticalAlert = false,
/// Request permission to provisionally create non-interrupting notifications.
/// Defaults to `false`.
///
/// iOS only.
bool provisional = false,
/// Request permission to play sounds. Defaults to `true`.
///
/// iOS/macOS only.
bool sound = true,
}) {
return _delegate.requestPermission(
alert: alert,
announcement: announcement,
badge: badge,
carPlay: carPlay,
criticalAlert: criticalAlert,
provisional: provisional,
sound: sound,
);
}
/// Send a new [RemoteMessage] to the FCM server. Android only.
Future<void> sendMessage({
String? to,
Map<String, String>? data,
String? collapseKey,
String? messageId,
String? messageType,
int? ttl,
}) {
if (ttl != null) {
assert(ttl >= 0);
}
return _delegate.sendMessage(
to: to ?? '${app.options.messagingSenderId}@fcm.googleapis.com',
data: data,
collapseKey: collapseKey,
messageId: messageId,
messageType: messageType,
ttl: ttl,
);
}
/// Enable or disable auto-initialization of Firebase Cloud Messaging.
Future<void> setAutoInitEnabled(bool enabled) async {
return _delegate.setAutoInitEnabled(enabled);
}
/// Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery for Android.
///
/// On iOS, you need to follow [this guide](https://firebase.google.com/docs/cloud-messaging/understand-delivery?platform=ios#enable_delivery_data_export_for_background_notifications)
/// in order to export metrics to BigQuery.
/// On Web, you need to setup a [service worker](https://firebase.google.com/docs/cloud-messaging/js/client) and call `experimentalSetDeliveryMetricsExportedToBigQueryEnabled(messaging, true)`
Future<void> setDeliveryMetricsExportToBigQuery(bool enabled) async {
return _delegate.setDeliveryMetricsExportToBigQuery(enabled);
}
/// Sets the presentation options for Apple notifications when received in
/// the foreground.
///
/// By default, on Apple devices notification messages are only shown when
/// the application is in the background or terminated. Calling this method
/// updates these options to allow customizing notification presentation behavior whilst
/// the application is in the foreground.
///
/// Important: The requested permissions and those set by the user take priority
/// over these settings.
///
/// - [alert] Causes a notification message to display in the foreground, overlaying
/// the current application (heads up mode).
/// - [badge] The application badge count will be updated if the application is
/// in the foreground.
/// - [sound] The device will trigger a sound if the application is in the foreground.
///
/// If all arguments are `false` or are omitted, a notification will not be displayed in the
/// foreground, however you will still receive events relating to the notification.
Future<void> setForegroundNotificationPresentationOptions({
bool alert = false,
bool badge = false,
bool sound = false,
}) {
return _delegate.setForegroundNotificationPresentationOptions(
alert: alert,
badge: badge,
sound: sound,
);
}
/// Subscribe to topic in background.
///
/// [topic] must match the following regular expression:
/// `[a-zA-Z0-9-_.~%]{1,900}`.
Future<void> subscribeToTopic(String topic) {
_assertTopicName(topic);
return _delegate.subscribeToTopic(topic);
}
/// Unsubscribe from topic in background.
Future<void> unsubscribeFromTopic(String topic) {
_assertTopicName(topic);
return _delegate.unsubscribeFromTopic(topic);
}
}
void _assertTopicName(String topic) {
bool isValidTopic = RegExp(r'^[a-zA-Z0-9-_.~%]{1,900}$').hasMatch(topic);
assert(isValidTopic);
}