Firebase Cloud Messaging
Firebase Cloud Messaging (FCM) is a cross-platform Messaging solution that lets you reliably send messages for free.
Using FCM, you can notify a client application that new E-mail messages or other data can be synchronized. You can send notification messages to promote user re-engagement and retention. For use cases such as instant messaging, a single message can transmit a payload of up to 4 KB to the client application.
The following is based on version 1.22.4 of the Flutter
The preparatory work
Before starting, this document assumes that you can create (or have an existing) Flutter project and that you also have a Firebase project in use. If you do not meet these prerequisites, refer to the preparations
The installation
1. Add dependencies
dependencies:
flutter:
sdk: flutter
firebase_core: "^ 0.5.3"
firebase_messaging: 11 "" ^ 8.0.0 - dev.
Copy the code
2. Download dependencies
$ flutter pub get
Copy the code
3. The ios integration
Reference: firebase. Flutter. Dev/docs/messag…
4. The android integration
If you are using the Flutter Android Embedding V2 (Flutter version > = 1.12), no additional integration steps are required for Android. — Me, for example.
For details about earlier versions, see Flutte Accessing Firebase Messaging
use
Before using Firebase Cloud Messaging, you must first make sure that FlutterFire is initialized.
await Firebase.initializeApp();
Copy the code
Incoming messages are handled differently depending on the state of the device. To understand these situations and how to integrate FCM into your own applications, it is important to first determine the various states that devices can be in:
state | describe |
---|---|
Foreground | When the application is open and displayed in the foreground. |
Background | When the application is opened, but in the background (minimal). This typically occurs when the user presses the “Home” button on the device to switch to another application via the application switcher or to open an application on another TAB (Web). |
Terminated | When the device is locked or the application is not running. The user can terminate the application by “brushing it off” or by closing the TAB (Web) on the application switcher user interface on the device. |
-
In either case, the application must be opened at least once (to allow registration in FCM, it must be able to connect to Google).
-
On Android, if you force an application to terminate, you won’t get push.
-
On iOS, if the user swipes the app from the app switcher, they must manually reopen it again for the background messages to start working again.
License Application (ios, Mac and Web)
On iOS, macOS, and the Web, the user must be asked for permission before receiving the FCM payload on the device.
You don’t need to request permissions on your Android application.
Code:
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,);print('User grant permission result:${settings.authorizationStatus}');
Copy the code
The authorizationStatus attribute can return a value that can be used to determine the user’s overall decision:
authorized
: The user has been granted permission.denied
: The user denied the permission.notDetermined
: The user has not selected whether to grant a license.provisional
: The user granted temporary permissions (see temporary Permissions) (Firebase. Flutter. Dev/docs/messag…
On Android, authorizationStatus is always Authorized.
The other properties on NotificationSettings return whether certain permissions are enabled, disabled, or not supported on the current device.
For more information, see the Permissions document.
Process the message
Message type
Depending on the current state of the application, incoming payloads require different implementations to handle them:
Foreground | Background | Terminated | |
---|---|---|---|
Notification | onMessage |
onBackgroundMessage |
onBackgroundMessage |
Data | onMessage |
onBackgroundMessage (*see below*) |
onBackgroundMessage (*see below*) |
Notification & Data | onMessage |
onBackgroundMessage |
onBackgroundMessage |
Foreground message
By default, notifications that arrive when the app is in the foreground do not show up as visible notifications on either Android or iOS. However, this action can be overwritten: flutter_LOCAL_notifications is used in the foreground to display a notification when a push is received.
///The front desk news
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Get a message at reception! ');
if(message.notification ! =null) {
RemoteNotification notification = message.notification;
///According to notice
if(notification ! =null&& notification.android ! =null) {
FlutterLocalNotificationsPlugin().show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
// TODO adds the appropriate drawable resource to Android (under Drawable)
icon: 'launch_background', ), ), payload: message.data.toString()); }}});Copy the code
Background messages
Currently, the process of processing background messages is different on Android/Apple and Web-based platforms.
Processing messages is a little different when the application is running in the background. Messages can be processed through the onBackgroundMessage handler.
When the quarantine message is received, the quarantine message is generated (for Android only, iOS/macOS does not require separate quarantine messages, APNS is awesome) and can be processed even if your application is not running.
Here are some things to keep in mind about the way messages are handled in the background:
- It cannot be an anonymous function.
- It must be a top-level function (for example, not a class method that needs to be initialized).
static Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print("Background message received:${message.messageId}"); }...///The background information
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
Copy the code
When background messages are received, running heavy tasks for a long time affects device performance and may cause the operating system to terminate the process. If the task takes longer than 30 seconds, the device may automatically terminate the process.
OnMessageOpenedApp: This stream sends RemoteMessage when the application is opened from the background state. You can listen to the user clicking on the notification:
///Click the background message to open the App
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Open from the background! ');
});
Copy the code
Click on the Terminated notification to open App (Terminated)
OnBackgroundMessage cannot listen to the behavior of such notifications, but it can receive the user’s click behavior for such notifications:
GetInitialMessage () : If the application is opened from the terminated state, the Future containing RemoteMessage will be returned. Once used, RemoteMessage will be removed.
///The application is opened from the terminated state
var m = await FirebaseMessaging.instance.getInitialMessage();
if(m ! =null) {
print('The application is opened from the terminated state:${m? .notification? .title}');
}
Copy the code
To display notifications must containnofitication
field
Process interactions
Because notifications are visible prompts, users typically interact with notifications by clicking on them. The default behavior on Android and iOS is to open the app. If the application terminates, it starts; If it is in the background, it will be brought to the foreground.
The FireBase-Messaging package provides two ways to handle this interaction (mentioned above, but highlighted again) :
- GetInitialMessage () : If the application is opened from the terminated state, the Future containing RemoteMessage will be returned. Once used, RemoteMessage will be removed.
- OnMessageOpenedApp: This stream sends RemoteMessage when the application is opened from the background state.
You are advised to handle both cases.
///Click the background message to open the App
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Open from the background! ');
});
///The application is opened from the terminated state
var m = await FirebaseMessaging.instance.getInitialMessage();
if(m ! =null) {
print('The application is opened from the terminated state:${m? .notification? .title}');
}
Copy the code
Here’s an official example:
class Application extends StatefulWidget {
@override
State<StatefulWidget> createState() => _Application();
}
class _Application extends State<Application> {
@override
void initState() async {
super.initState();
// Get any messages which caused the application to open from
// a terminated state.
RemoteMessage initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
// If the message also contains a data property with a "type" of "chat",
// navigate to a chat screen
if(initialMessage? .data['type'] = ='chat') {
Navigator.pushNamed(context, '/chat',
arguments: ChatArguments(initialMessage));
}
// Also handle any interaction when the app is in the background via a
// Stream listener
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
if (message.data['type'] = ='chat') {
Navigator.pushNamed(context, '/chat', arguments: ChatArguments(message)); }}); }@override
Widget build(BuildContext context) {
return Text("..."); }}Copy the code
How you handle the interaction depends on your application setup, but the above example shows a basic example of using the StatefulWidget.
For foreground notifications click, check flutter_LOCAL_notifications for Settings.
The theme
Users can subscribe to a topic, and when we send a push, we send a push to a topic, and people who subscribe to that topic will receive it.
Serves as a push to multiple users.
The main thing is THAT I didn’t find out how to send a push to all users when I got it over HTTP.
Subscribe to topics:
To subscribe to a device, call the subscribeToTopic method with the topic name:
await FirebaseMessaging.instance.subscribeToTopic('weather');
Copy the code
Unsubscribe topic
To unsubscribe a topic, call the unsubscribeFromTopic method with the topic name:
await FirebaseMessaging.instance.unsubscribeFromTopic('weather');
Copy the code
The meaning here is that the subject name is weather.
Sending push messages through Http
If you cannot use the Firebase Admin SDK, Firebase also supports sending messages to the device via HTTP, POST requests:
Project_id: indicates the project ID of Firebase
Authorization: server Authorization key
POST to https://fcm.googleapis.com/v1/projects/ {project_id} / messages: HTTP / 1.1 / send/request header content-type: application/json Authorization: Bearer ya29.ElqKBGN2Ri_Uz... HnS_uNreA //body { "message":{ "token":"token_1", "data":{}, "notification":{ "title":"FCM Message" "body":"This is an FCM notification message!" ,}}}Copy the code
A sample project based on this write has been published to Github
Android and ios push have been tuned in the background and tested on multiple phones.