Implementing the MIDlet MainView class

The MainView class is used for implementing functionality to register the MIDlet and receive notifications from the Nokia Notification Server.

To implement the MainView class:

  1. Create the MainView.java class file.

    package com.nokia.example.nnaclientexample;
  2. Import the required classes and packages.

    import java.util.Calendar;
    
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.StringItem;
    
    import com.nokia.notifications.NotificationError;
    import com.nokia.notifications.NotificationException;
    import com.nokia.notifications.NotificationInfo;
    import com.nokia.notifications.NotificationMessage;
    import com.nokia.notifications.NotificationSession;
    import com.nokia.notifications.NotificationSessionFactory;
    import com.nokia.notifications.NotificationSessionListener;
    import com.nokia.notifications.NotificationState;
  3. Create the MainView class to extend Form, implement CommandListener, NotificationSessionListener.

    The MIDlet uses the NotificationSessionListener interface to get notified when a Nokia notifications message or info is received, or when the notification status changes.

    public class MainView
    	extends Form
    	implements CommandListener, NotificationSessionListener
  4. Ceate the required variables and constants.

    private static final int ERROR = 0;
    private static final int STATUS = 1;
    private static final int NOTIFICATION_ID = 2;
    private static final int NOTIFICATION_MESSAGE = 3;
    private static final String[] MESSAGE_TYPE_STRING =
        { "Error", "Status", "Notification ID", "Notification" };
    private static final String ABOUT_TEXT =
        "This simple example demonstrates the use of Nokia Notifications API.";
    
    private Main main = null;
    private NotificationSession session = null;
    private final Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private final Command registerCommand = new Command("Register", Command.OK, 1);
    private final Command unregisterCommand = new Command("Unregister", Command.OK, 2);
    private final Command cancelCommand = new Command("Cancel", Command.CANCEL, 1);
    private final Command getIdCommand = new Command("Get Notification ID", Command.OK, 1);
  5. Create the MainView class constructor, and in the constructor, create a Nokia notifications session using the NotificationSessionFactory class, which allows the MIDlet to communicate with the Notification Enabler.

    public MainView(Main main) {
        super("NNA Client Example");
    
        this.main = main;
    
        addCommand(registerCommand);
        addCommand(exitCommand);
        setCommandListener(this);
    
        StringItem aboutItem = new StringItem("About", ABOUT_TEXT);
        append(aboutItem);
    
        addLogMessage(STATUS, "Offline");
    
        try {
            session =
                NotificationSessionFactory.openSession(
                    main, // The MIDlet instance
                    "example.com", // Service ID (Deprecated)
                    "com.example", // Application ID
                    this); // NotificationSessionListener
        }
        catch (NotificationException ne) {
            addLogMessage(ERROR, ne.toString());
        }
    }
  6. Implement the following methods from the NotificationSessionListener interface to get the MIDlet notified when a notification message or info is received, or when the status changes.

    public void infoReceived(NotificationInfo info) {
        String notificationId =  info.getNotificationId();
    
        if (notificationId.length() == 0) {
            addLogMessage(ERROR, "Received notification ID is empty!");
        }
        else {
            addLogMessage(NOTIFICATION_ID, notificationId);
            System.out.println("Notification ID :-" + notificationId);
        }
    
        removeCommand(getIdCommand);
    }
    
    public void messageReceived(NotificationMessage message) {
        addLogMessage(NOTIFICATION_MESSAGE, message.getPayload().getData());
    }
    
    public void stateChanged(NotificationState state) {
        switch (state.getSessionState()) {
        case NotificationState.STATE_OFFLINE:
            deleteAll();
            removeCommand(unregisterCommand);
            removeCommand(cancelCommand);
            addCommand(registerCommand);
            addLogMessage(STATUS, "Offline");
            break;
        case NotificationState.STATE_CONNECTING:
            deleteAll();
            removeCommand(registerCommand);
            addCommand(cancelCommand);
            addLogMessage(STATUS, "Connecting");
            break;
        case NotificationState.STATE_ONLINE:
            deleteAll();
            removeCommand(registerCommand);
            removeCommand(cancelCommand);
            addCommand(getIdCommand);
            addCommand(unregisterCommand);
            addLogMessage(STATUS, "Online");
            break;
        default:
            addLogMessage(STATUS, "Unknown");
            break;
        }
    
        final int error = state.getSessionError();
    
        if (error != NotificationError.ERROR_NONE) {
            addLogMessage(ERROR, notificationStateErrorCodeToString(error));
        }
    }
  7. Implement the methods from the CommandListener interface to capture UI events and handle them to call the respective functions call for notification and UI updates.

    public void commandAction(Command command, Displayable display) {
        if (command == registerCommand) {
            try {
                session.registerApplication();
            }
            catch (NotificationException ne) {
                addLogMessage(ERROR, ne.toString());
            }
        }
        else if (command == cancelCommand || command == unregisterCommand) {
            removeCommand(getIdCommand);
    
            try {
                session.unregisterApplication();
            }
            catch (NotificationException ne) {
                addLogMessage(ERROR, ne.toString());
            }
        }
        else if (command == getIdCommand) {
            try {
                session.getNotificationInformation();
            }
            catch (NotificationException ne) {
                addLogMessage(ERROR, ne.toString());
            }
        }
        else if (command == exitCommand) {
            session.close();
            main.quit();
        }
    }
  8. Create the addLogMessage method to display time — hour, minute, and second on the screen.

    private void addLogMessage(int messageType, String message) {
        Calendar calendar = Calendar.getInstance();
        StringBuffer time = new StringBuffer().append(
            calendar.get(Calendar.HOUR_OF_DAY)).append(":");
    
        if (calendar.get(Calendar.MINUTE) < 10) {
            time.append('0');
        }
    
        time.append(calendar.get(Calendar.MINUTE)).append(":");
    
        if (calendar.get(Calendar.SECOND) < 10) {
            time.append('0');
        }
    
        time.append(calendar.get(Calendar.SECOND));
    
        String messageTypeString = null;
    
        try {
            messageTypeString = MESSAGE_TYPE_STRING[messageType];
        }
        catch (ArrayIndexOutOfBoundsException e) {
            messageTypeString = "???";
        }
    
        StringItem item =
            new StringItem(time.toString() + " " + messageTypeString, message,
                           StringItem.PLAIN);
        append(item);
    }
  9. Create the notificationStateErrorCodeToString method to display the error messages (If any exceptions occurs in any notification state) on the screen.

    private String notificationStateErrorCodeToString(final int errorCode) {
        String errorMessage = null;
    
        switch (errorCode) {
        case NotificationError.ERROR_APPLICATION_ID_CONFLICT:
            errorMessage = "The Application ID has already been registered by another MIDlet.";
            break;
        case NotificationError.ERROR_APPLICATION_ID_INVALID:
            errorMessage = "The Application ID is either empty or more than 255 characters long.";
            break;
        case NotificationError.ERROR_AUTHENTICATION_FAILED:
            errorMessage = "The device is not able to fetch the authentication details from the Notification server.";
            break;
        case NotificationError.ERROR_CONNECTION_DISABLED_BY_USER:
            errorMessage = "The user has disabled connections like WiFi and cellular network.";
            break;
        case NotificationError.ERROR_DISABLED_BY_USER:
            errorMessage = "The user has disabled  notifications.";
            break;
        case NotificationError.ERROR_NO_NETWORK:
            errorMessage = "The Notification Enabler has lost connection with the Notification server.";
            break;
        case NotificationError.ERROR_NONE:
            errorMessage = "No error.";
            break;
        case NotificationError.ERROR_NOT_ALLOWED:
            errorMessage = "NotificationSession is not in correct state.";
            break;
        case NotificationError.ERROR_NOT_KNOWN:
            errorMessage = "Other Notification error.";
            break;
        case NotificationError.ERROR_NOT_REGISTERED:
            errorMessage = "MIDlet is not registered, but is calling for a function that requires registration.";
            break;
        case NotificationError.ERROR_REGISTER_FAILED:
            errorMessage = "Registration failed because there is not enough space available in the device memory to store the settings.";
            break;
        case NotificationError.ERROR_SERVICE_UNAVAILABLE:
            errorMessage = "Notification Server is not available.";
            break;
        case NotificationError.ERROR_SESSION_CLOSED:
            errorMessage = "NotificationSession function call failed because session was closed.";
            break;
        default:
            errorMessage = "Unknown error.";
            break;
        }
    
        return errorMessage;
    }
    }