Android

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:

Push Notification Via Cloud Code App

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:

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 the GCMSenderId that you obtained at Firebase in the AndroidManifest.xml file.

  1. 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;
    
  2. Initialize Parse with Parse.initialize(this).
  3. Create a new array of channels and put the channels you would like to subscribe. In this example, the News channel is created.
  4. Add to your installation your GCMSenderId, obtained from the Firebase Console, through the command installation.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.

  5. Add the channels object to the installation through the command installation.put("channels", channels).
  6. 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.

  1. Create a .js file to put your Cloud Code into. In this example, a main.js file is created.
  2. Define a Cloud function, using Parse.Cloud.Define, to call the push notification. In this example, this function is called Parse.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 });
});

main.js

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

  1. Go to your App at Back4App website and click on Dashboard.
  2. Find the Cloud Code and click on Functions & Web Hosting. It looks like this:

    Cloud Code block

  3. Upload or create a new file (you can also edit the current main.js file directly on the browser). Then, click at Deploy as shown here:

    Cloud Code Settings

Step 4 - Call Cloud Code from Android App

  1. 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;   
    
  2. Call the ParseCloud.callFunctionInBackground on the pushsample 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();
     }
    
  3. 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!