TechPosts

Local Notifications in Codename One

Local notifications are similar to push notifications, except that they are initiated locally, by the app, rather than remotely. They are useful for communicating information to the user while the app is running in the background, since they manifest themselves as pop-up notifications on supported devices.

Sending Notifications

The API for sending local notifications is similar to the java.util.Timer and java.util.TimerTask APIs in that you can schedule a notification to occur as some time in the future, and have it repeat at a set interval if you like.

Key differences:

  1. Timer only runs while the app itself is running. Local notifications don’t require the app to be running. The OS will wake up the app if necessary when a local notification is received.

  2. A local notification may not ever be received by the app. The user will see the notification pop up on their device and they can either choose to "click" on it to enter the app, or they can choose to ignore it.

Example Sending Notification

LocalNotification n = new LocalNotification();
n.setId("Hello");
n.setAlertBody("Hello World");
n.setAlertTitle("Look Here");
n.setFireDate(System.currentTimeMillis() + 5000);
n.setRepeatType(LocalNotification.REPEAT_MINUTE);
n.setAlertSound("beep-01a.mp3");
Display.getInstance().sendLocalNotification(n);

Receiving Notifications

The API for receiving/handling local notifications is more similar to push. Your application’s main lifecycle class needs to implement the com.codename1.notifications.LocalNotificationCallback interface which includes a single method:

public void localNotificationReceived(String notificationId)

The notificationId parameter will match the id value of the notification as set using LocalNotification.setId().

Example Receiving Notification

public class BackgroundLocationDemo implements LocalNotificationCallback {
    //...

    public void init(Object context) {
        //...
    }

    public void start() {
        //...

    }

    public void stop() {
        //...
    }

    public void destroy() {
        //...
    }

    public void localNotificationReceived(String notificationId) {
        System.out.println("Received local notification "+notificationId);
    }
}

Canceling Notifications

Repeating notifications will continue until they are canceled by the app. You can cancel a single notification by calling:

Display.getInstance().cancelAllLocalNotifications();

You can cancel only a specific notification by calling

Display.getInstance().cancelLocalNotification(notificationId);

Where notificationId is the string id that was set for the notification using LocalNotification.setId().