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

Hello.
This is Goto from the Web Development Department.

last time, this time Ionic2 with an example of using push notificationsI'd like to write about
GCM (Google Cloud Messaging) We will be using

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

located in the root directory of your Ionic project
is defined in the `app_id` field within the `ionic.config.json` file
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

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,"IAM & Admin => Settings"you can check it under

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.
in Google APIs "API Manager => Credentials"You can find it

That's all

If you found this article helpful,please give it a "Like"!
0
Loading...
0 votes, average: 0.00 / 10
955
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author