[TypeScript] Example of using push notifications with ionic2 [Android]
Hello.
My name is Goto from the web development department.
last time , this time I would like to write an
example of how to use push notifications in Ionic2 Uses GCM (Google Cloud Messaging)
This one.
import { Push, provideCloud, CloudSettings } from '@ionic/cloud-angular'; const SENDER_ID = "{GCM project number}"; const cloudSettings: CloudSettings = { 'core': { 'app_id': '{App's ID}' }, 'push': { 'sender_id': SENDER_ID } }; @Component({omitted}) class MyApp { constructor(private platform: Platform, private push: Push) { this.platform.ready().then (() => { var myPush = new Push.init( android: { sender_id: SENDER_ID } ); push.on('registration', (id) => { console.log(id); // => {registration id} is output }); push.on('notification', (data) => { console.log(data.title); console.log(data.message); }); push.on('error ', (e) => { console.log(e.message); }); }); } } ionicBootstrap(MyApp, [provideCloud(cloudSettings)]);
However, this alone does not work
Introduce what you need.
1. Install the plugin
$ ionic plugin add phonegap-plugin-push --variable SENDER_ID="{Project number}"
2. Install the module
$ npm install --save @ionic/cloud-angular
Operation confirmation
curl -X POST -H "Authorization: key={Authorization key}" -H "Content-Type: application/json" -d '{ "registration_ids": ["{Registration ID for push notification}"], " data": { "title" : "It's terrible", "message": "Specifically, my stomach feels terrible" } }' "https://android.googleapis.com/gcm/send"
supplementary explanation
I will write a brief but supplementary explanation for those who are wondering about the following that appeared in the source code
- App ID
- GCM project number
- registration id
- Authentication key
What is that? I will write a brief supplementary explanation for those who think so.
App ID
The app ID
is the ID defined in app_id written in "ionic.config.json" located in the root directory of the Ionic project.
I think the name used when creating the project using the ionic command is reflected as is.
If not, set it up yourself.
GCM project number
this , let's create a project.
When you create a project, a "project ID" and "project number" will be issued.
The project number is used in push notifications.
If you have already created one, you can check it from "IAM and Management => Settings"
registration id
This is issued by the smartphone.
Once it is published, send it to the server.
When the server side wants to send a push notification,
it makes a request to GCM to push to the smartphone with that ID.
Authentication key
This is the authentication key when requesting push notifications to GCM.
You can check it in "API Manager => Authentication Information" of GoogleAPIs
That's it.