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

Hello,
this is Goto from the Web Development Department.

last time , this time I would like to write
an example of how to use push notifications with Ionic 2. I will use 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 of you who are confused about the following that appears in the source code, here is a simple
supplementary 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


is the ID defined in the app_id field in the "ionic.config.json" file
located in the root directory of your Ionic project It should reflect the name you used when creating the project using the ionic command.
If not, set it yourself.

GCM project number

this page , create a project.
When you create a project, you will be issued a "Project ID" and "Project Number."
This project number will be used for push notifications.
If you have already created one, you can check it by going to "IAM & Admin => Settings."

registration id

This 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 push to the smartphone with that ID.

Authentication Key

This is the authentication key used to send push notification requests to GCM.
You can check this in Google APIs' "API Manager => Authentication Information"

That's all

If you found this article useful, please click [Like]!
0
Loading...
0 votes, average: 0.00 / 10
923
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author