4
votes

I'm trying to find out how to push proper notifications using Codename One servers. I'd like to send notifications which basically look like LocalNotifications - with title, body, badge etc.

However in the documentation for push servers there seems to be just one field concerning the notification payload:

  • body - the body of the message.

Q1: How to push(server side through Codename One server) and display(Codename One app) a notification with title and body from the server?

I'd like be able to send and receive custom data in the payload too, e.g. reference to some app content which should be opened in the app when opening the app "from" that particular push notification.

Q2: Can I send basically anything as a notification body, even my own JSON?

In the Codename One API there is this callback interface PushCallback, specifically method void push(String value). Is this callback intended exactly for the purpose of "pre-processing/parsing" of the notification payload just before displaying it as a LocalNotification?

Thanks.

1

1 Answers

2
votes

There are various types of push messages you can send in Codename One, namely 0,1,2,3,4,5,100, and 101.

If you require the title and the body, set your push type to 4 and separate your title and body with ; in your payload.

If you require a push with some hidden content which you can use to manipulate your app in the background, go for push type 3. Separate the visible and hidden payloads with ;. The hidden section is where you put your JSON string, just ensure the vissible message doesn't start with { or [. A php payload example will look something like this:

$vissibleMsg = "Cum ut quia delectus libero hic.";
$jsonString = json_encode(array("action" => "openMainForm", "id" => "1", "message" => $vissibleMsg));

$payload = $vissibleMsg . ";" . $jsonString;

And in your push(String value), read the hidden JSON content like this:

@Override
public void push(String value) {
    Display.getInstance().callSerially(() -> {
        if (value.startsWith("{") || value.startsWith("[")) {
            try {
                JSONObject response = new JSONObject(value);

                switch (response.getString("action")) {
                    case "openMainForm":
                        //do whatever you want here
                        break;
                    default:
                        //perform default action here
                        break;
                }
            } catch (JSONException err) {
                Log.e(err);
            }
        }
    });
}

If you require a hidden content and a visible content with title and body, then you will have to send the push twice using type 2 and type 4 respectively, based on the link I shared above.