[TypeScript] Example of using push notifications with ionic2 [Android]

table of contents
Hello.
This is Goto from the Web Development Department.
Following on from last time , this time I'd like to write about an example of using push notifications with Ionic2 . We will be using 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 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 printed }); 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 will not work
We will 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 check
curl -X POST -H "Authorization: key={Authentication key}" -H "Content-Type: application/json" -d '{ "registration_ids": ["{Registration ID for push notification}"], "data": { "title" : "Bad", "message": "Specifically, my stomach feels bad" } }' "https://android.googleapis.com/gcm/send"
supplementary explanation
For those who are confused by the following points in the source code, I will
provide a brief explanation.
- App ID
- GCM project number
- registration id
- Authentication Key
What is that? I will write a simple supplementary explanation for those who are wondering
App ID
The app ID is defined in the `app_id` field within the `ionic.config.json` file located in the root directory of your Ionic project . It should be the same name you used when creating the project using the `ionic` command. If not, you'll need to set it yourself.
GCM project number
Once you access this page , create a project. When you create a project, a "Project ID" and a "Project Number" will be issued. The Project Number is the one you'll use for push notifications. If you've already created a project, you can check it under "IAM & Admin => Settings"
registration id
This ID is issued on the smartphone side.
Once issued, send it to the server.
When the server wants to send a push notification,
it will request GCM to send a push notification to the smartphone with that ID.
Authentication Key
This is the authentication key used when making push notification requests to GCM. You can find it in Google APIs under "API Manager => Credentials"
That's all
0
