JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

Embed Size (px)

Citation preview

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    1/26

    J.E.D.I.

    Optional Packages

    1 Objectives

    In this section, we will be delving into writing, building, using the emulator andpackaging J2ME applications. The Integrated Programming Environment that we will beusing is Netbeans (www.netbeans.org).

    After finishing this lesson, the student should be able to:

    know the functionalities provided by the Mobile Media API

    play simple tones

    play an audio file from the network and from the JAR

    send and receive SMS messages

    2 Overview

    Not all devices are created equal and each device class comes with different features. Itwould be very difficult to create a standard specification that encompass all the existing

    devices.

    To accomodate the different capabilities of devices, MIDP has defined several optionalpackages. These packages are specific to and cater only to the specific device feature.

    In this section, we will be discussing how to start using the Mobile Media API (MMAPI)and the Wireless Messaging API (WMA).

    3 Mobile Media API (MMAPI)

    The Mobile Media API (MMAPI) allows us to generate tones, play and record audio andvideo on compatible devices.

    Playing or recording media is handled by two objects: the DataSource and the Player.

    Mobile Application Development 1

    http://www.netbeans.org/http://www.netbeans.org/
  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    2/26

    J.E.D.I.

    The DataSource handles the details of getting the data from the source. The source maybe a file from the JAR or from the network (via HTTP), a record from the RMS, astreaming connection from a server or other proprietary source. The Player does nothave to worry about where the data came from or the manner in which it would befetched. All the Player has to do is to read the data from the DataSource, process and

    display or playback the media to the output device.

    A third actor in our scene is the Manager. The Manager creates players fromDataSources. The Manager has methods to create Players from media locators (URLlocations), DataSources and InputStreams.

    You can query MMAPI properties via the String System.getProperty(String key).

    Key Description

    microedition.media.version The version of the MMAPI specificationimplemented by the device. Example: "1.1"

    supports.mixing Returns "true" if the device supports audiomixing: can play at least two tonessimultaneously, can have at least twoPlayers playing audio simultaneously andcan play a tone even if at least one Playeris playing audio at the same time.

    Mobile Application Development 2

    DataSource Player

    DataSource Player

    Manager

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    3/26

    J.E.D.I.

    Key Description

    supports.audio.capture returns the String "true" if audio capture issupported. returns "false", otherwise.

    supports.video.capture returns the String "true" if video capture issupported. returns "false", otherwise.

    supports.recording returns "true" if recording is supported.

    3.1 Tone generation

    Playing a tone is as simple as calling the static method Manager.playTone(int tone, intduration, int volume). The valid values for the tone is from 0 to 127. The duration of theplaying of the tone is specified in milliseconds. The volume parameter is from 0 to 100.

    import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;

    import javax.microedition.media.*;

    import javax.microedition.media.control.*;

    import java.io.*;

    public class ToneMIDlet extends MIDlet implements CommandListener{

    private Command exitCommand, playCommand;

    private Form form;

    private Gauge volumeGauge;

    private Gauge durationGauge;

    private Gauge toneGauge;

    private Display display;

    private int duration = 2; // seconds

    private int volume = 100;

    private int tone = ToneControl.C4;

    private static int MAX_VOLUME = 100;

    private static int MAX_TONE = 127;

    private static int MAX_DURATION = 5;

    public ToneMIDlet() {

    playCommand = new Command("Play", Command.OK, 1);

    exitCommand = new Command("Exit", Command.EXIT, 1);

    Mobile Application Development 3

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    4/26

    J.E.D.I.

    volumeGauge = new Gauge("Volume", true, MAX_VOLUME, volume);

    toneGauge = new Gauge("Tone", true, MAX_TONE, tone);

    durationGauge = new Gauge("Duration",true,MAX_DURATION,duration);

    form = new Form("Tone Player");

    form.addCommand(playCommand);

    form.addCommand(exitCommand);

    form.append(volumeGauge);

    form.append(durationGauge);

    form.append(toneGauge);

    }

    public void startApp() {

    display = Display.getDisplay(this);

    form.setCommandListener(this);

    display.setCurrent(form);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable d) {

    if (c == exitCommand) {

    notifyDestroyed();

    }

    if (c == playCommand){

    try {

    volume = volumeGauge.getValue();

    tone = toneGauge.getValue();

    duration = durationGauge.getValue();

    Manager.playTone(tone, duration*1000, volume);

    } catch (MediaException mex){}

    }

    }

    }

    Mobile Application Development 4

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    5/26

    J.E.D.I.

    3.2 Audio playback

    The convenience method Manager.createPlayer(String URI) creates a player which willplay the data from the URI.

    import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;

    import javax.microedition.media.*;

    import javax.microedition.media.control.*;

    import java.io.*;

    public class NetAudioMidlet extends MIDlet implements CommandListener{

    private Command exitCommand, playCommand;

    private Form form;

    private Gauge volumeGauge;

    private Display display;

    private int volume = 100;

    private static int MAX_VOLUME = 100;

    Player player;

    public NetAudioMidlet() {

    playCommand = new Command("Play", Command.OK, 1);

    exitCommand = new Command("Exit", Command.EXIT, 1);

    volumeGauge = new Gauge("Volume", true, MAX_VOLUME, volume);

    form = new Form("Audio Player");

    form.addCommand(playCommand);

    form.addCommand(exitCommand);

    form.append(volumeGauge);

    }

    public void startApp() {

    display = Display.getDisplay(this);

    form.setCommandListener(this);

    display.setCurrent(form);

    Mobile Application Development 5

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    6/26

    J.E.D.I.

    try {

    player = Manager.createPlayer(

    "http://localhost:8084/Chapter07/bong.wav ");

    player.realize();

    // pre-fetch media to reduce latency

    player.prefetch();

    } catch (IOException ioex) {

    display.setCurrent(new Alert("IO Exception",

    ioex.getMessage(),null, AlertType.ERROR));

    } catch (MediaException mex) {

    display.setCurrent(new Alert("Media Exception",

    mex.getMessage(),

    null, AlertType.ERROR));

    }

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable d) {

    if (c == exitCommand) {

    notifyDestroyed();

    }

    if (c == playCommand){

    try {

    VolumeControl control = (VolumeControl)

    player.getControl("VolumeControl");

    if (control != null){

    control.setLevel(volumeGauge.getValue());

    }

    player.start();

    } catch (MediaException mex) {

    Mobile Application Development 6

    http://localhost:8084/Chapter07/bong.wavhttp://localhost:8084/Chapter07/bong.wav
  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    7/26

    J.E.D.I.

    display.setCurrent(new Alert("Media Exception",

    mex.getMessage(), null, AlertType.ERROR));

    } catch (Exception ex){

    display.setCurrent(new Alert("Exception",

    ex.getMessage(), null, AlertType.ERROR));

    }

    }

    }

    }

    You can also play media from a file in the JAR by creating a Stream from the fileresource and passing it to Manager.createPlayer().

    import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;

    import javax.microedition.media.*;

    import javax.microedition.media.control.*;

    import java.io.*;

    public class AudioMidlet extends MIDlet implements CommandListener{

    private Command exitCommand, playCommand;

    private Form form;

    private Gauge volumeGauge;

    private Display display;

    private int volume = 100;

    private static int MAX_VOLUME = 100;

    Player player;

    public AudioMidlet() {

    playCommand = new Command("Play", Command.OK, 1);

    exitCommand = new Command("Exit", Command.EXIT, 1);

    volumeGauge = new Gauge("Volume", true, MAX_VOLUME, volume);

    form = new Form("Audio Player");

    form.addCommand(playCommand);

    Mobile Application Development 7

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    8/26

    J.E.D.I.

    form.addCommand(exitCommand);

    form.append(volumeGauge);

    }

    public void startApp() {

    display = Display.getDisplay(this);

    form.setCommandListener(this);

    display.setCurrent(form);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable d) {

    if (c == exitCommand) {

    notifyDestroyed();

    }

    if (c == playCommand){

    try {

    InputStream stream = getClass().

    getResourceAsStream("bong.wav");

    player = Manager.createPlayer(stream, "audio/x-wav");

    player.realize();

    VolumeControl control = (VolumeControl)

    player.getControl("VolumeControl");

    if (control != null){

    control.setLevel(volumeGauge.getValue());

    }

    player.start();

    } catch (MediaException mex) {

    display.setCurrent(new Alert("Media Exception",

    mex.getMessage(), null, AlertType.ERROR));

    } catch (Exception ex){

    display.setCurrent(new Alert("Exception",

    Mobile Application Development 8

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    9/26

    J.E.D.I.

    ex.getMessage(), null, AlertType.ERROR));

    }

    }

    }

    }

    4 Wireless Messaging API (WMA)

    4.1 Sending SMS

    Using the Wireless Messaging API is very similar to connection via Sockets andDatagrams. In fact, it uses the same framework the Generic Connection Framework(GCF). The connection URL format to use is "sms://+639178888888", where"+639178888888" is the number of the phone you want to send messages to.

    public void sendSMS(String number, String message) throws Exception{

    String url = "sms://" + number;

    MessageConnection connection =

    (MessageConnection) Connector.open(url);

    TextMessage msg = (TextMessage) connection.newMessage(MessageConnection.TEXT_MESSAGE);

    msg.setPayloadText(message);

    connection.send(msg);

    connection.close();

    }

    Development of wireless applications on Netbeans 4.1 is very convenient. You don't haveto send actual SMS messages just to test your application. Netbeans (with mobility pack)

    comes with J2ME Wireless Toolkit. This toolkit comes with an emulator. It also includestools for testing sending and receiving SMS messages. You can configure the phonenumber (address) of the emulated phone by opening the WMA preferences.

    Tools

    Java Platform Manager

    J2ME Wireless Toolkit 2.2

    Tools and Extensions

    Open Preferences -> WMA

    Mobile Application Development 9

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    10/26

    J.E.D.I.

    Open Utilities -> WMA: Open Console

    Mobile Application Development 10

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    11/26

    J.E.D.I.

    Mobile Application Development 11

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    12/26

    J.E.D.I.

    Mobile Application Development 12

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    13/26

    J.E.D.I.

    Mobile Application Development 13

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    14/26

    J.E.D.I.

    import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;

    import javax.microedition.io.*;

    import javax.wireless.messaging.*;

    public class SMSMidlet extends MIDlet implements CommandListener, Runnable{

    private Command exitCommand, sendCommand;

    private Form form;

    private TextField addressField, mesgField;

    private Display display;

    public SMSMidlet() {

    sendCommand = new Command("Send", Command.OK, 1);

    exitCommand = new Command("Exit", Command.EXIT, 1);

    addressField = new TextField(

    "Phone Number", "+5550000", 32, TextField.ANY);

    mesgField = new TextField(

    "Message", "hello, world!", 160, TextField.ANY);

    form = new Form("SMS Message");

    form.append(addressField);

    form.append(mesgField);

    form.addCommand(sendCommand);

    form.addCommand(exitCommand);

    }

    public void startApp() {

    display = Display.getDisplay(this);

    form.setCommandListener(this);

    display.setCurrent(form);

    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    Mobile Application Development 14

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    15/26

    J.E.D.I.

    public void commandAction(Command c, Displayable d) {

    if (c == exitCommand) {

    notifyDestroyed();

    }

    if (c == sendCommand) {

    Thread thread = new Thread( this );

    thread.start();

    }

    }

    /**

    * Sends an SMS message to number. This method will throw an exception* if there is an error in connecting or sending the message.

    * @param number

    * @param message

    */

    public void sendSMS(String number, String message) throws Exception{

    String url = "sms://" + number;

    MessageConnection connection =

    (MessageConnection) Connector.open(url);

    TextMessage msg = (TextMessage) connection.newMessage(

    MessageConnection.TEXT_MESSAGE);

    msg.setPayloadText(message);

    connection.send(msg);

    connection.close();

    }

    public void run() {

    try {

    String address = addressField.getString();

    String message = mesgField.getString();

    sendSMS(address, message);

    display.setCurrent(new Alert("SMS Message",

    "Message Sent\n"

    + "To: " + address + "\n"

    + "Message: " + message,

    null, AlertType.INFO));

    Mobile Application Development 15

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    16/26

    J.E.D.I.

    } catch (Exception ex) {

    display.setCurrent(new Alert("SMS Error", ex.getMessage(),

    null, AlertType.ERROR));

    }

    }

    }

    Mobile Application Development 16

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    17/26

    J.E.D.I.

    Mobile Application Development 17

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    18/26

    J.E.D.I.

    Mobile Application Development 18

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    19/26

    J.E.D.I.

    4.2 Receiving SMS

    To receive a text message, open a MessageConnection specifying a port. The protocolstring for SMS messaging is "sms". This command will listen for incoming SMS messagesfrom port 8888:

    conn = (MessageConnection) Connector.open("sms://:8888");

    We must register our application to be a Message Listener so that the AMS will notify ourMIDlet of incoming messages.

    conn.setMessageListener(this);

    The notifyIncomingMessage will be called by the AMS once a message is received by the

    device. We will need to create a separate Thread for reading messages so that theListener callback method can exit immediately.

    public void notifyIncomingMessage(MessageConnection messageConnection) {

    if (thread == null){

    thread = new Thread(this);

    thread.start();

    }

    }

    Mobile Application Development 19

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    20/26

    J.E.D.I.

    In our run() method, we are now ready to get the message:

    public void run(){

    try {

    // wait for and receive message

    Message mesg = conn.receive();

    // Received a message

    // Check if this is a text message (and not MMS, etc.)

    if (mesg != null && mesg instanceof TextMessage) {

    TextMessage text = (TextMessage) mesg;addressField.setText(text.getAddress());

    mesgField.setText(text.getPayloadText());

    dateField.setText("" + text.getTimestamp());

    statusField.setText("Message received.");

    }

    } catch (Exception e) {

    statusField.setText("Error: " + e.getMessage());

    }

    thread = null;

    }

    Here is the complete source code listing for our SMS Receiver:

    import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;

    import javax.microedition.io.*;

    import javax.wireless.messaging.*;

    public class SMSReceiverMidlet extends MIDlet

    implements CommandListener, MessageListener, Runnable {

    private Command exitCommand, sendCommand;

    private Form form;

    private StringItem statusField, addressField, mesgField, dateField;

    private Display display;

    Mobile Application Development 20

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    21/26

    J.E.D.I.

    private MessageConnection conn;

    private Thread thread;

    private String port = "8888";

    public SMSReceiverMidlet() {

    exitCommand = new Command("Exit", Command.EXIT, 1);

    statusField = new StringItem("Status:", "");

    addressField = new StringItem("From:", "");

    mesgField = new StringItem("Message:", "");

    dateField = new StringItem("Timestamp:", "");

    form = new Form("SMS Receiver");

    form.append(statusField);

    form.append(addressField);

    form.append(mesgField);

    form.append(dateField);

    form.addCommand(exitCommand);

    }

    public void startApp() {

    display = Display.getDisplay(this);

    form.setCommandListener(this);

    startReceiver();

    display.setCurrent(form);

    }

    public void pauseApp() {

    thread = null;

    }

    public void destroyApp(boolean unconditional) {

    thread = null;

    if (conn != null){

    try {

    conn.close();

    } catch (Exception ex){}

    Mobile Application Development 21

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    22/26

    J.E.D.I.

    }

    }

    public void commandAction(Command c, Displayable d) {

    if (c == exitCommand) {

    notifyDestroyed();

    }

    }

    private void startReceiver(){

    try {

    String addr = "sms://:" + port;if (conn == null){

    conn = (MessageConnection) Connector.open(addr);

    conn.setMessageListener(this);

    statusField.setText(

    "waiting for message at port " + port);

    }

    } catch (Exception ex){

    statusField.setText("Cannot open connection on port "

    + port + ":" + ex.getMessage());

    }

    thread = new Thread(this);

    thread.start();

    }

    public void notifyIncomingMessage(MessageConnection messageConn){

    if (thread == null){

    thread = new Thread(this);

    thread.start();

    }

    }

    public void run(){

    try {

    Mobile Application Development 22

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    23/26

    J.E.D.I.

    // wait for and receive message

    Message mesg = conn.receive();

    // Received a message

    // Check if this is a text message (and not MMS, etc.)

    if (mesg != null && mesg instanceof TextMessage) {

    TextMessage text = (TextMessage) mesg;

    addressField.setText(text.getAddress());

    mesgField.setText(text.getPayloadText());

    dateField.setText("" + text.getTimestamp());

    statusField.setText("Message received.");

    } else {statusField.setText(

    "Non-text message received: "

    + mesg.getClass().toString());

    }

    } catch (Exception e) {

    statusField.setText("Error: " + e.getMessage());

    }

    thread = null;

    }

    }

    Mobile Application Development 23

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    24/26

    J.E.D.I.

    Mobile Application Development 24

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    25/26

    J.E.D.I.

    Mobile Application Development 25

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson09-Optional Packages

    26/26

    J.E.D.I.

    5 Exercises

    5.1 Audio Player

    Create a MIDlet that will play an audio file for an idefinite number of times (loop). Theaudio file should be read from the JAR. Hint: you must set a property on the Player tocontrol the looping.

    5.2 SMS Auto-Responder

    Create a MIDlet that will automatically reply when it receives a text message. Hint: youcan modify the SMSReceiverMidlet and use the same connection to send the replymessage.

    Mobile Application Development 26