Push notifications between Ionic 2/3 apps using FCM
After searching the web for noob friendly process to use FCM(firebase cloud messaging), I finally decided to follow the official documentation. Here it goes for Android. I will refer the app receiving the notification as App1 and the sending app as App2.
Make a new project in firebase console.
Go to Notifications and select Android.
Package name is the id of your App1 as mentioned in your config.xml. Click on register app
Download the google-services.json and place it in the root of your project folder .
Skip to console in firebase
Install the Cordova and Ionic Native plugins in App1:
ionic cordova plugin add cordova-plugin-fcmnpm install --save @ionic-native/fcm
Add the plugin to the app.module.ts file’s imports[] array.
import { FCM } from '@ionic-native/fcm';providers: [
FCM,
...
]
In your app.components.ts
Inject fcm in the constructor()
import { FCM } from '@ionic-native/fcm';constructor(private fcm: FCM, ...) {...}
inside the platform.ready() use the following code.
platform.ready().then(() => {
//Notifications
fcm.subscribeToTopic('all');
fcm.getToken().then(token=>{
console.log(token);
})
fcm.onNotification().subscribe(data=>{
if(data.wasTapped){
console.log("Received in background");
} else {
console.log("Received in foreground");
};
})
fcm.onTokenRefresh().subscribe(token=>{
console.log(token);
});
//end notifications.
statusBar.styleDefault();
splashScreen.hide();
});
For detailed explanation visit the fcm github page .
Run on your device
ionic cordova run android --device
App2 Sending Notifications
In app.module.ts
import {HttpClientModule} from '@angular/common/http';imports: [BrowserModule,HttpClientModule,...
]
In the typescript file of the page from where you want to send the notification in App2
import { HttpClient } from '@angular/common/http/';
import { HttpHeaders } from '@angular/common/http';
constructor( private http: HttpClient,...) {...}//Add this function and call it where you want to send it.sendNotification()
{
let body = {
"notification":{
"title":"New Notification has arrived",
"body":"Notification Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"/topics/all",
"priority":"high",
"restricted_package_name":""
}
let options = new HttpHeaders().set('Content-Type','application/json');
this.http.post("https://fcm.googleapis.com/fcm/send",body,{
headers: options.set('Authorization', 'key=YourAuthToken'),
})
.subscribe();
}
To get your auth token, head back to firebase. Go to project settings> Cloud Messaging Tab.
Again don’t forget to call the above sendNotification() function.
Run on your device or ionic serve
ionic cordova run android --device
Note:
id of both your apps should be different, otherwise the second app install will override the previous one.
Claps if I helped.