Send Parse push notifications using Cloud Code
Introduction
This section explains how you can send push notifications using Cloud Code through Back4App.
This is how it will look like:
At any time, you can access the complete Android Project built with this tutorial at our GitHub repository.
Prerequisites
To complete this tutorial, you need:
- Android Studio
- An app created on Back4App.
- Note: Follow the New Parse App Tutorial to learn how to create a Parse App on Back4App.
- An Android app connected to Back4app.
- Note: Follow the Install Parse SDK Tutorial to create an Android Studio Project connected to Back4App.
- Follow the Steps 1 to 5 of Back4App Push Notifications via Dashboard tutorial carefully to set up Push Notifications to your app.
- A device (or virtual device) running API level 27 or newer.
Step 1 - Set up Android to receive push
Every Parse application installed on a device registered for push notifications has an
associated Installation
object. The Installation
object is where you store all the data
needed to target push notifications. For example, in your app, you could store which
teams one of your users is interested in to send updates about their performance. Saving the
Installation
object is also required for tracking push-related app open events.
The simplest way to start sending notifications is using channels. This allows you to use a
publisher-subscriber model for sending pushes. Devices start by subscribing to one or more
channels, and notifications can later be sent to these subscribers. The channels subscribed
to by a given Installation
are stored in the channels
field of the Installation
object.
To start working with push notifications, the following steps are required:
If you downloaded our project template, don’t forget to change your credentials in the
app/src/main/res/values/string.xml
file and theGCMSenderId
that you obtained at Firebase in theAndroidManifest.xml
file.
- Import the following dependecies:
1 2 3 4 5
// Java Dependencies import java.util.ArrayList; // Parse Dependencies import com.parse.Parse; import com.parse.ParseInstallation;
- Initialize Parse with
Parse.initialize(this)
. - Create a new array of channels and put the channels you would like to subscribe. In this example, the
News
channel is created. - Add to your installation your
GCMSenderId
, obtained from the Firebase Console, through the commandinstallation.put("GCMSenderId", "YOUR_FIREBASE_GCM_SENDER_ID_HERE")
.To know how you can obtain that key, look at Step 1 of Push Notifications via Dashboard tutorial.
- Add the
channels
object to theinstallation
through the commandinstallation.put("channels", channels)
. - Save the installation to your database through
installation.saveInBackground()
.
The following code executes these steps:
1
2
3
4
5
6
7
8
Parse.initialize(this);
ArrayList<String> channels = new ArrayList<>();
channels.add("News");
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
// don't forget to change the line below with the sender ID you obtained at Firebase
installation.put("GCMSenderId", "YOUR_FIREBASE_GCM_SENDER_ID_HERE");
installation.put("channels", channels);
installation.saveInBackground();
Step 2 - Create your Cloud Code
To know more about how to get started with Cloud Code look at Cloud Code for Android Tutorial.
- Create a
.js
file to put your Cloud Code into. In this example, amain.js
file is created. - Define a Cloud function, using
Parse.Cloud.Define
, to call the push notification. In this example, this function is calledParse.Push.Send
.It is required to use the master key in this operation.
The following code executes these steps:
main.js
1
2
3
4
5
6
7
8
9
10
Parse.Cloud.define("pushsample", (request) => {
return Parse.Push.send({
channels: ["News"],
data: {
title: "Hello from the Cloud Code",
alert: "Back4App rocks!",
}
}, { useMasterKey: true });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Parse.Cloud.define("pushsample", function (request, response) {
Parse.Push.send({
channels: ["News"],
data: {
title: "Hello from the Cloud Code",
alert: "Back4App rocks!",
}
}, {
success: function () {
// Push was successful
response.success("push sent");
console.log("Success: push sent");
},
error: function (error) {
// Push was unsucessful
response.error("error with push: " + error);
console.log("Error: " + error);
},
useMasterKey: true
});
});
Step 3 - Upload to Cloud Code
- Go to your App at Back4App website and click on
Dashboard
. - Find the
Cloud Code
and click onFunctions & Web Hosting
. It looks like this: - Upload or create a new file (you can also edit the current
main.js
file directly on the browser). Then, click atDeploy
as shown here:
Step 4 - Call Cloud Code from Android App
- Import the following dependencies:
1 2 3 4 5 6
// Java Dependencies import java.util.HashMap; // This includes the HasMap Object that the Cloud function needs to call // Parse Dependencies import com.parse.FunctionCallback; import com.parse.ParseCloud; import com.parse.ParseException;
- Call the
ParseCloud.callFunctionInBackground
on thepushsample
cloud function:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
final HashMap<String, String> params = new HashMap<>(); // Calling the cloud code function ParseCloud.callFunctionInBackground("pushsample", params, new FunctionCallback<Object>() { @Override public void done(Object response, ParseException exc) { if(exc == null) { // The function was executed, but it's interesting to check its response alertDisplayer("Successful Push","Check on your phone the notifications to confirm!"); } else { // Something went wrong Toast.makeText(MainActivity.this, exc.getMessage(), Toast.LENGTH_LONG).show(); } } });
The
alertDisplayer
method used in the example above is the following:1 2 3 4 5 6 7 8 9 10 11 12 13
private void alertDisplayer(String title,String message){ AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this) .setTitle(title) .setMessage(message) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog ok = builder.create(); ok.show(); }
- Test if the push notifications are being sent by calling the function above while the device is opened.
Step 5 - Call Cloud Code from REST API
The REST API provides a quick and easy way to test if your Cloud function is working.
Just use the code below in your terminal or command prompt:
Click on to know more about how to get started with command line in Linux, MacOS
or Windows.
curl -X POST -H "X-Parse-Application-Id: YOUR_APP_ID_HERE" \
-H "X-Parse-REST-API-Key: YOUR_REST_API_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ // Put the function parameters here in JSON format }' \
https://parseapi.back4app.com/functions/pushsample
To test the push notifications, just use the REST code while the device is opened.
It’s done!
At this stage, you can send push notifications using Cloud Code through Back4App!