Technical Articles

PhoneGap Tutorial 1 Push Notifications (Part 2)

You should now have created, tested, built and understand how to release a mobile application for iOS and Android using PhoneGap developer. We are going to develop the application from Part 1 of the tutorial to add Push Notifications. Again you should allow approximately 2 hours for the second part of this tutorial, if you find this tutorial useful please share using the share buttons and comment on the post. If you have any questions and would like to contact me directly please use the contact tab at the bottom of the page. Good luck with the second part of the tutorial – you have made it this far so lets add some wings to this app!

NOTE: The source code for all our tutorials is available on public repositories via BitBucket and Git. The source code for this repository can be downloaded via a git shell or terminal (Linux) using the below command

There is another important step here you need to do a search and replace of ‘www/’ and remove it from all the icon and screen references in the config.xml file. All the source locations are relative to the config.xml file so the entries need to look like this src=”res/icon/an……..

You need to update the below line in the config.xmlFROM

1

<preference name="android-minSdkVersion"value="14"/>

TO

1

<preference name="android-minSdkVersion"value="16"/>

Add the Push Configuration code to the config.xml file at the end before the </widget> tag

Note: we are using a very recent version of the push plugin, this is because up until version 2.0 of the plugin iOS needed to use APNS as opposed to Firebase.
We are also configuring the locations the Firebase configuration files need to be for the plugin on each OS to read them succesfully.
These configuration files hold details such as API keys and Sender ID’s. It is for this reason that we can’t test Push notifications correctly using the PhoneGap developer app as the app is not aware of the configuration for Firebase until the apps are built (this is different to previous versions of the plugin where the SENDER_ID was maintained in the config.xml or specified in the PushNotification.init procedure). There may be a way around this and I will post into this tutorial if I find any workarounds to test in PhoneGap developer.
We are also specifying a higher version of the PhoneGap CLI for PhoneGap build as this is required for the newer versions of the push notification plugin.

The config.xml file should now be correctly configured, we will configure index.js this is located in the www/js directory.

Firstly we will add a new function to the onDeviceReady function as below

1

2

3

4

5

6

.........

onDeviceReady:function(){

app.receivedEvent('deviceready');

app.setupPush();

},

..........

Next we will add the new setupPush function to the end of the index.js script (Comments descrive the function of each component in the setupPush function.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

...........

// New application Push setup function

setupPush:function(){

//Initialise Push Notifications

varpush=PushNotification.init({

"android":{},

"ios":{

"sound":true,

"alert":true,

"badge":true

},

"windows":{}

});

//Function that executes once registered with Firebase

push.on('registration',function(data){

console.log("registration event: "+data.registrationId);

console.log("device type: "+device.platform);

document.write('<div>'+data.registrationId+'</div>');

});

//Error handler

push.on('error',function(e){

console.log("push error: "+e.message);

});

//Function that executes when a notification is received

push.on('notification',function(data){

console.log('notification event received');

navigator.notification.alert(

data.message,// message

null,// callback

data.title,// title

'Ok'// buttonName

);

});

//Push finish setup function

push.finish(function(){

console.log('Push Setup Success');

},function(){

console.log('Push Setup Error');

});

}

........

Your full index.js script should now look like below

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

/*

* Licensed to the Apache Software Foundation (ASF) under one

* or more contributor license agreements. See the NOTICE file

* distributed with this work for additional information

* regarding copyright ownership. The ASF licenses this file

* to you under the Apache License, Version 2.0 (the

* "License"); you may not use this file except in compliance

* with the License. You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing,

* software distributed under the License is distributed on an

* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

* KIND, either express or implied. See the License for the

* specific language governing permissions and limitations

* under the License.

*/

varapp={

// Application Constructor

initialize:function(){

this.bindEvents();

},

// Bind Event Listeners

//

// Bind any events that are required on startup. Common events are:

// 'load', 'deviceready', 'offline', and 'online'.

bindEvents:function(){

document.addEventListener('deviceready',this.onDeviceReady,false);

},

// deviceready Event Handler

//

// The scope of 'this' is the event. In order to call the 'receivedEvent'

// function, we must explicitly call 'app.receivedEvent(...);'

onDeviceReady:function(){

app.receivedEvent('deviceready');

app.setupPush();

},

// Update DOM on a Received Event

receivedEvent:function(id){

varparentElement=document.getElementById(id);

varlisteningElement=parentElement.querySelector('.listening');

varreceivedElement=parentElement.querySelector('.received');

listeningElement.setAttribute('style','display:none;');

receivedElement.setAttribute('style','display:block;');

console.log('Received Event: '+id);

},

// New application Push setup function

setupPush:function(){

//Initialise Push Notifications

varpush=PushNotification.init({

"android":{},

"ios":{

"sound":true,

"alert":true,

"badge":true

},

"windows":{}

});

//Function that executes once registered with Firebase

push.on('registration',function(data){

console.log("registration event: "+data.registrationId);

console.log("device type: "+device.platform);

document.write('<div>'+data.registrationId+'</div>');

});

//Error handler

push.on('error',function(e){

console.log("push error: "+e.message);

});

//Function that executes when a notification is received

push.on('notification',function(data){

console.log('notification event received');

navigator.notification.alert(

data.message,// message

null,// callback

data.title,// title

'Ok'// buttonName

);

});

//Push finish setup function

push.finish(function(){

console.log('Push Setup Success');

},function(){

console.log('Push Setup Error');

});

}

};

Our push code is now complete we are ready to build the apps and test on Android and iOS. As above the latest version of the plugin is very difficult to test on the PhoneGap developer app.

Build and Test Push Notification App

Firstly you need to build your app by zipping up the ‘www’ directory and uploading to PhoneGap developer.

You may need to unlock your keys again as per the instructions in Part 1 of the tutorial by clicking on the lock icon and entering your key passwords.

You should now see your iOS and Android apps built as below, please note the Windows app no longer generates after removing the config.xml code.

You should now download your .ipa .apk and move your latest www.zip to the releases directory as per the instructions in Part 1 of the tutorial

We now have built binaries with Push notifications enabled and Firebase configured we just need to test the binaries now.

Install the newly created binaries

Android Installation

With Android we can manually install the .apk file. In some cases there may be a setting on your device that prevents the installation of 3rd Part APK’s i.e. those that don’t come directly from the Play Store, if so you need to locate this setting and disable it, it is different on most devices but is usually in a ‘settings’ -> ‘security’ area.

Firstly we need to make the binaries public in PhoneGap build, so login to PhoneGap, from the ‘Settings’ tab check the ‘Allow public sharing’ setting and then ‘Save’

You will now see a share icon on your app as below you need to click this

At the next screen you will get options to download the .ipa and .apk files. You need to make a note of the URL of this page and open this on your mobile device

You should now be able to download install and run this on your Android device. Once executed and after the device is ready you should see a screen similar to below

The string being dislpayed is the Firebase registration ID, you need to transfer this from your device to your own machine, it is a very long string so you have a number of options, you can select all/copy the string then either email it to yourself from your device, save it on a cloud area from your device accessible by your machine, send it to yourself via an IM or another method. This string will only change when you install a new version of the application and is required in the next part of the tutorial to send a test Push Notification.

iOS Installation

iOS is a little more restrictive as we can’t install the .ipa directly onto the device as we can on Android and again you will need a Mac to upload the .ipa to iTunesConnect so you can test it on TestFlight.

I am happy to do this for a small ‘beer money’ donation 🙂 and much cheaper than some Internet sites out there advertise!

If you make a $10 donation to my paypal account I will upload an ipa file to your iTunesConnect account 5 times, you can make a donation safely using the paypal link below, once you have made the payment please email paypal@gothai.land and attach your .ipa file and your iTunesConnect login details, also include the id you made the paypal payment with if it is not the same as the email address you send the .ipa from. All requested uploads will made within 12 hours. If you are uncomfortable handing over your login details I am happy to do a screen share using Skype or Teamviewer to show the .ipa being uploaded and me using your login details (you can change your login details right after the upload) however this will cost 2 upload credits of the 5 you purchase.

A lot of work has gone into this series of tutorials so donations do not hurt the cause of me adding to the series 🙂

If you have any queries around this process please contact me online by using the “Support Agent Online” tab at the bottom of the page.

Many thanks for contributing!

Test Push Notifications

We are going to look at two methods to test push notifications, first using the Firebase console itself, then secondly using a third party tool (Postman) to send a JSON message to the server and deliver. Sending a message using JSON and Postman will emaulate if you have a third party application that needs to initiate push notifications to the mobile applications. If a third party application needed to send targeted push notifications to devices say for example based on User ID’s then the Firebase Registration ID’s linked to these userid’s could be stored in a database table and used by the application to know where to send messages. I will try to cover functionality like this in a future tutorial.

Test Push notifications using the Firebase Console

We can use the Firebase console itself to initiate a push notification to the device, we have various options here we could sent to an individual device, a group of specific device types, a specific topic we have created or to all users registered with the application, we will look at a couple of these options.

Send to an individual device

In the section above when testing this on your android device you should have copied the Firebase registration ID to your computer you will need this for the next step.

Open up Firebase console and select Notifications from the ‘Grow’ section

From the Notifications screen select ‘Send Message’ and populate the screen below, notice my Firebase registration ID is the same as the one I noted above, and again select ‘Send Message’ review the message and ‘Send’

The message should then come through to your device in a similar fashion to below.

Send to all devices registered

This time in the send message screen you need to seelct the button ‘Target Another App’ this allows you to select both your Android devices and iOS devices.

Sending the message now will result in the message being sent to all registered devices.

Test Push notifications using the Postman API app

This is where the testing gets quite interesting. A lot of third party applications have the ability to send out external messages in a JSON format. Generally there are just a few things required and firebase push notifications are no different.

An API URL – in the case of Firebase this is https://fcm.googleapis.com/fcm/send

An API registration Key – This is located in your Project settings -> Cloud Messaging Tab, it is defined as the ‘Server Key’

A JSON message – in the case of Firebase this is fairly straight forward, it contains the registration ID of the device you are sending the message to and the message itself.

Lets send a message

Firstly start Postman and create a new message, to start with we have to populate 2 header keys, Content-Type and Authorization as below, Content-Type is always the same for Firebase messages, and Authorization is our ‘Server Key’

Next we need to populate the message body with the JSON message itself as below then select ‘Send’
The text for my message above is

Congratulations, you should now have created a basic push notification app, tested it using PhoneGap developer, built the application using Production certificates and be in a position to release it to the app stores.

Obviously you would need to add a few bells and whistles to make this a viable app but the structure is there.

If you found this tutorial useful again please leave a comment or if you have any questions ask them in the comment boxes below, also please share the tutorial links.

Archives

About Us

Gothai.land are an independent IT consultancy with 20+ years experience specialising in Oracle Database, Oracle Business Intelligence, Web/Mobile development, Application Express development, cloud technology and much more