Firebase message push on android with the system tray

Firebase is the most widely used message push tool on Android. If the Android app on the background, both received and processed messages are processed by the system. So this article will introduce and provide a demo project for quick testing FCM.

Notification in Android

You can find details from the official document here.

Firebase Push

You can find details from the official document here.

Usually, if your app runs in the background, the notification will display with the system tray. And if it runs in the foreground, Firebase SDK will call onMessageReceived() to pass payload for making notification yourselves.

Server Implement

Here is a demo project is written using JavaScript.

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
var admin = require("firebase-admin");

var serviceAccount = require("./thisIsYourProjectAccountFile.json");

admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});


// This registration token comes from the client FCM SDKs.
var registrationToken = 'ThisIsYourTokenWhichGenerateByMobile';

var message = {
notification: {
title: "this is title",
body: "this is body",
},
data: {
badge:"1",
sound:"default",
deeplink:"https://www.google.com"
},
android: {
notification: {
image: "https://images.pexels.com/photos/97076/pexels-photo-97076.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500"
}
},
token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});

The token is generated by Firebase mobile SDK.

Android Implement

1
2
3
4
5
6
7
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(
this
) { instanceIdResult: InstanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
findViewById<TextView>(R.id.tv_main).text = newToken
}