Firebase+Ionic: How to use cloud messaging within Ionic and Capacitor with ChatGPT support?
Firebase cloud messaging is an efficient and easy way to distribute a notification or a piece of data from a system to smartphone end users. Even it is a well documented in the official web page and there are many articles, I believe most of them do not show how to develop an application in a short amount of time in the scope of the integration of Ionic framework, Firebase Cloud Messaging(FCM) service and Capacitor. In this tutorial, all required components will be explained to realize such an application from the server side implementation to the client side through the following major steps:
- Implementing an ionic application integrating capacitor push notification
- Testing App in Android Pixel Emulator
- Understanding Firebase Cloud Messaging Types
- Configuring a Firebase Account and an App Creation
- Testing Ionic App on Android Emulator
- Implementing a Content Distributor via Python
Please remember, the software libraries can be overtime outdated, and always check the validity of the libraries before you start to save the time.
Before starting the following steps, it is noteworthy to mention that the steps below are performed in OSx environment, therefore it will differ slightly from Windows development environment. By the way, do not forget to install Android Studio
beforehand :).
1. Ionic App Implementation & Integration of Capacitor Push Notification
Ionic app is another try of developing android or iOS application using web frameworks. It uses the novel feature of android and iOS framework features to build nice looking applications. From this perspective, we may think ionic framework uses a web server in a native application. All the communication with the hardware components are performed through Capacitor framework. In order to be able to receive messages as notification, the notification of the service of the android OS should be used, therefore, in capacitor push notification
plugin is one of the essential component in this use case.
The implementation of an ionic app integrating capacitor push notification is composed of a number of steps, which have to be carefully performed.
These are:
- check the
node
version, if not, for the Mac OSX environment
$node --version
if not available and you have a Homebrew installed:
$brew install node@16
- assuming that
node
installation is done beforehand from the official website,ionic/cli
library should be installed:
npm install -g @ionic/cli
- Create a simple ionic app via:
ionic start fcm-app blank --type=angular
cd fcm-app/
npx cap init
The final command above requests the app-name
and package-id
such as fcm-app
and com.xyz.fcmapp
.
Once these processes are performed, ionic should be built successfully and the platform related folder should be created as shown below:
ionic build
after ionic build
, you should be able to access the webpage via
ionic serve
command on the terminal, which opens a web server with http://localhost:8100
Once the page is opened, you will see the following view
- Add
android
platform and then add the android related folder
npm install @capacitor/android
npx cap add android
The result of the last command:
This means, the Java version is outdated and the gradle
version coming while adding android library requires Java 11.
The installation of Java 11 is composed of two steps, first install Java 11 and then add the installation path in .bash_profile
. If you don't know how to do it, here is the link from another medium author.
- Install capacitor plugin
In case there is no issue, we can now install capacitor/push-notification plugin and synchronize with the android folder, simply calling the commands:
npm install @capacitor/push-notifications
npx cap sync
- add required code for handling FCM operations
Depending on your source code, you can add the following code block wherever you wish, in this case we add it simply in the home component.
import { Component, OnInit } from '@angular/core';
import {
ActionPerformed,
PushNotificationSchema,
PushNotifications,
Token,
} from '@capacitor/push-notifications';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
ngOnInit() {
console.log('Initializing HomePage');
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
PushNotifications.requestPermissions().then(result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener('registration', (token: Token) => {
console.log(token.value);
alert('Push registration success, token: ' + token.value);
});
PushNotifications.addListener('registrationError', (error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotificationSchema) => {
alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: ActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
},
);
}
}
The code piece above is suggested by ChatGPT, however, it was also available in this link. All the meaning of the functions written in the code are explained in the capacitor website. If you have knowledge in Java how a plugin works behind the scene between capacitor and ionic, it is recommended to look at this GitHub link as well.
The code says shortly we will receive aregistration-token
through the registration process to FCM and regarding the selected message type, notification, data or both, we can receive the message content directly within the app, or outside the app as a notification. Once the application is finalized, we need to build ionic app and synchronize with the android/ folder as below:
ionic build
npx cap copy
2. Testing App in Android Pixel 4 Emulator
Android Studio provides a number of emulator to test your application. All these tests are performed via Pixel 4 mit API level 31. You may also install this emulator under Device Manager and run this application in the emulator.
- Create A Virtual Device by navigating Device Manager > Click Create Device > Select Pixel 4 API 31, and then install it.
2. Install Android SDK under Preferences> System Settings > Android SDK for Android 12.0. Notice that you won’t receive a notification without installing it.
3. Now, we can run the application by selecting the Pixel 4 Emulator. Once the app is booted, you will see the emulator on the right side under Device Manager. The content of the message will be the same as shown in the previous steps once the ionic serve
is executed.
3. Understanding Firebase Cloud Messaging Types
FCM offers many different features while transmitting a notification message. Before having received a message, first the android device should be registered, which is explained in the previous section. At every new installation of the application, a new device registration will occur, and all this registration operation are handled by Firebase.
Now, on the ionic
side we don’t define any message type, however, while creating the app in the FCM and while sending message from an application to FCM, the message type is needed. For this reason, we need to first understand what are the available message types. From the official google web page, there are threemessage types
:
notification
: The message is directly handled by the android notification system, and the message content cannot be used within the app. In other words, the notification message and its content will land in the phone whether the app is running in the foreground or background. Once the app is opened, the transmitted message content will not available in the app. The message format is given below:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
data
: The incoming data will be processed directly in the application itself, this means the message will not be handled by the android OS notification handler, in other words an android service will receive and process it. Whether the app is in the foreground or background, this is not important, since a continuously running service should be executed. The message format is based onkey:value
format as shown below:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
notification+data
: The notification message is handled by the android notification system, in addition, once it is opened, the hanging data payload will be also available in the app. A simple message to be received can be shown as follows:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
}
All messages are taken from official website.
For our example, the notification
message is enough, since our purpose is simply to send a notification from a python app to an android app. The creation of the message will be performed in the following section, we need first create an FCM app withing Firebase platform.
4. Firebase Account Configuration and Android App Creation
The creation of an app in Firebase is a well-known topic, therefore there are many resources that explain it pretty well. For example, this link shows step by step the app creation and the needed modifications in the android app later on. If we summarize the required steps, they can be explained in three steps:
- Create a Firebase project
- Create an application based on the android under the Firebase project
- Enter the android
project-id
, package namecom.xyz.fcmapp
and storegoogle-service.json
, which will be used later in the ionic project.
In the end of these steps, you should have a file google-service.json
file that will be placed in the android/app/
folder. Please notice that android
folder is the generated folder by ionic
framework which includes all necessary files. After adding this file, you can also test your app as shown below whether it receives the message:
- Click Add project
2. Enter the project name
3. You can enable or disable Google Analytics, in this case it is disabled.
4. Once the project is created, it will direct you the following page, you can click android
icon, marked with red color, to create an app.
5. The package name of the app is already given while creating ionic
app in the previous steps, we add it here com.xyz.fcmapp
. The nickname can be added as well.
6. In the second step, you need to download goole-services.json
file and place it into android/app/
folder. By doing this step, we are done with the generation of the required ionic
app files.
7. The server side app requires another configuration file, in other words private key, to recognize firebase app, so that firebase app allows it to send a message. Below when you come over the app name, the settings icon will appear, you need to click it.
8. In the settings page, you should switch to Service accounts
, and generate a private key
with python
SDK. Once the Generate new private key is clicked, a file will downloaded, and it will be utilized within the server side application.
5. Testing Ionic App on Android Emulator
- Now, we can run the application by selecting the Pixel 4 Emulator. Once the app is booted, you will see the
registration
message will appear as seen below. This means FCM service registered this app, and deliver thedevice-token
.
2. Testing whether the notification app works or not, after adding google-services.json
in the android/app/
folder and recompiling it, you can click the Cloud Messaging box within Firebase project.
3. The previous step will direct you the following page in which you can click Create your first campaign button.
4. This step requires from you to select a message type. As mentioned above, we will use notification messages
. As stated in the following figure, notification mesasges gcan be received even if they are outside of the app, whereas in-app messages are receivedd when users are inside the app.
5. The following step is to create the notification title, and -text, and finally press the Send test message as shown below. This will send the notification message directly to your android application.
6. Add the FCM registration-token
in the displayed field, and for sending the message press Test button.
7. According to our implementation, if the app is in the forground, the push message will be displayed directly in the application. Please reming that, this is not the usual behavior, we implemented an alert message. In order to see what message is sent, you can log it.
8. If the application runs in the background or is completly shutted down. The notification message will be seen like all other notifications. In case you click it, your app will be opened. Once again, the message content that you send won’t be transfered into yout app, as long as you use notification
at this case.
6. Server Side Implementation for Sending Notifications to End users
To send the notification messages from an application, there are multiple ways to realize it. First, the FCM SDK supports different programming languages and distinguished communication protocols. We will use in this example HTTPs protocol, since it is the easiest one. The example code is given in the Firebase website. Even there is a good example, I asked ChatGPT how to send a message. It provided me two different examples, one with pyfcm
and the other with firebase-admin
. The important part is here to know, the registartion token
of the client who will receive the message should be known. This means you should store them somewhere, the reason, Firebase doesn’t deliver this information. If we come back to the implementation, here are the solutions:
Assuming that python
and pip
is installed on your platform, in this example we will usefirebase-admin
library since it is supported by the official website. To run the application we need registration token
and server-key
. The first information is already available from the first registration of the android application through the log messages, and the second one, server-key
, is generated also during the configuration of the firebase app.
The implementation is pretty simple, and you need to simply say to both libraries what you want to send and to whom and by providing your credentials.
!pip install firebase-admin
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/serviceAccountKey.json"
The file that I downloaded starts with task-notifier-42ec0-firebase-adminsdk-…json. This file should be assigned to GOOGLE_APPLICATION_CREDENTIALS
. The registration token of the android app should be placed in the code below. In the final step, you should execute the code.
from firebase_admin import messaging
import firebase_admin
try:
# Use the application default credentials
firebase_admin.initialize_app()
# This registration token comes from the client FCM SDKs.
registration_token = "YOUR_REGISTRATION_TOKEN"
# See documentation on defining a message payload.
message = messaging.Message(
notification=messaging.Notification(
title='Hello',
body='This is a test notification'
),
token=registration_token
)
# Send a message to the device corresponding to the provided
# registration token.
response = messaging.send(message)
# Response is a message ID string.
print(response)
except Exception as e:
print("An error occurred:", e)
Once you start this python script and it will send a message to FCM servers, and, the notification message will appear on the android emulator as below.
7. Bonus: A Makefile for ionic apps by ChatGPT
In order to simplify the implementation process as to ionic, I asked ChatGPT for the commands that are required for building an ionic application using a Makefile, here the result:
# Makefile for Ionic project
# Variables
PROJECT_NAME = myApp
# Ionic commands
start:
ionic start $(PROJECT_NAME) blank
serve:
ionic serve
generate:
ionic generate $(GENERATE_TYPE) $(GENERATE_NAME)
build:
ionic build $(PLATFORM)
run:
ionic run $(PLATFORM)
# Example usage
# make generate GENERATE_TYPE=page GENERATE_NAME=myPage
# make build PLATFORM=ios
# make run PLATFORM=android
It works pretty good, you can extend this file w.r.t your needs.
Summary
In this tutorial, we showed how FCM can be integrated into a server side app to distribute the messages to ionic application for android users. During the implementation steps, we experienced also the power of ChatGPT and demonstrated how it can simplify the implementation process for simple applications. I would recommend checking the generated code every time and even ChatGPT works well, we should not always trust what is generated.
References
- A similar approach for ionic implementation in https://devdactic.com/push-notifications-ionic-capacitor
- FCM with a native android app and python implementation, https://www.yippeecode.com/topics/android-firebase-cloud-messaging-in-python/