Push Notification using Cloud Code

Step 1: Set your app to receive push notifications:

You have to setup your app before using Push Notification on Cloud Code. Check out the guide below:

Push Notification via Dashboard

Then, you’ll have to understand how the Cloud Code works. Check out this guide:

Cloud Code for Android

After that, let’s configure the installation.

Step 2: Configure installation:

To send notifications via cloud code, you have to setup an Installation, so register it with this piece of code:

// Defines the channels this should listen to
LinkedList<String> channels = new LinkedList<String>();

// Pushes channelName
channels.push("channelName");

// Defines ParseInstallation
ParseInstallation installation = ParseInstallation.getCurrentInstallation();

// Adds the Firebase Sender Key
installation.put("GCMSenderId", "<Your Firebase Sender Key>");

// Adds the channel list to the installation
installation.put("channels", channels);
installation.saveInBackground();

Now the installation is registered in the channel called channelName.

Step 3: Make the .js file with the code for send the notification:

For work with cloud code, we need to code in JavaScript. Let’s make a code for send a notification with the message “Hello from the Cloud Code” to the channelName channel:

Parse.Cloud.define("pushsample", function (request, response) {
    Parse.Push.send({
        channels: ["channelName"],
        data: {
            title: "Hello!",
            message: "Hello from the Cloud Code",
        }
   }, {
        success: function () {
            // Push was successful
            response.sucess("push sent");
        },
        error: function (error) {
        // Push was unsucessful
        response.sucess("error with push: " + error);
        },
        useMasterKey: true
   });
});

Step 4: Upload the .js file to the back4app cloud:

Go to your app dashboard, click on Cloud Code -> Server:

Cloud Code

 

Next, click on “Choose file”, select the .js file, then click on “Save”:Cloud Code Upload

 

Step 5: Call it from the app, or from a REST API:

To call a cloud code function from the app, just use the following code:

// Create a HashMap<String, String> named functionParameters and push in the parameters you want
ParseCloud.callFunctionInBackground("pushSample", functionParameters, new FunctionCallback<Map<String, Object>> {
    @Override
    public void done(Object object, ParseException e) {
        // Do something after the function has been called
    }
});

To call a cloud code function from a REST API, use the code below:

curl -X POST -H "X-Parse-Application-Id: ${APPLICATION_ID}" \
-H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
-H "Content-Type: application/json" \
-d ‘{ // Put the function parameters here in JSON format }’ \
https://parseapi.back4app.com/functions/functionName