Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 38

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 38 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 382018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 38)

The Wireless Messaging API (WMA) specification defines APIs forsending and receiving SMS messages and receiving CBS messages. Atthe time of writing the current release of the Wireless Messaging API isversion 1.1. This contains minor modifications to the 1.0 specification toenable the API to be compatible with MIDP 2.0.The WMA is a compact API containing just two packages:• javax.microedition.io• javax.wireless.messaging.The first package contains the platform network interfaces modified foruse on platforms supporting wireless messaging connection, in particularan implementation of the Connector class for creating new MessageConnection objects.

The second package defines APIs whichallow applications to send and receive wireless messages. It defines a baseinterface Message from which BinaryMessage and TextMessageboth derive. It also defines a MessageConnection interface, whichprovides the basic functionality for sending and receiving messages, anda MessageListener interface for listening to incoming messages.In this section we shall consider sending and receiving SMS messages.We shall then go on to show how to use the Push Registry API of MIDP2.0 to register an incoming SMS connection with a MIDlet.190MIDP 2.0 AND THE JTWI3.4.4.2 Sending MessagesSending an SMS message using the WMA could not be simpler, as thecode paragraph below shows:String address = “sms://+447111222333”;MessageConnection smsconn = null;try {smsconn = (MessageConnection)Connector.open(address);TextMessage txtMessage =(TextMessage)smsconn.newMessage(MessageConnection.TEXT_MESSAGE);txtmessage.setPayloadText(“Hello World”);smsconn.send(txtMessage);smsconn.close();} catch (Exception e) {//handle}First we obtain a MessageConnection instance by invoking theConnector.open() method with an address of the appropriate syntax.A MessageConnection can operate in client or server mode dependingon the URL syntax of the address passed to the open() method.

For aclient mode connection (as used in the code listed above), messages canonly be sent. The URL address syntax for a client mode connection hasthe following possible formats:• sms://+447111222333• sms://+447111222333:1234The first format (as in the example above) is used to open a connectionfor sending a normal SMS message, which will be received in theend-user’s inbox.

The second format is used to open a connection tosend an SMS message to a particular Java application listening on thespecified port.The MessageConnector instance is then used to create a Messageinstance using the method:public Message newMessage(String type)The MessageConnection interface defines two public staticfinal String variables BINARY_MESSAGE and TEXT_MESSAGE. Iftype is equal to BINARY_MESSAGE an instance of BinaryMessageis returned, whereas if type equals TEXT_MESSAGE an instance of aTextMessage is returned. Both BinaryMessage and TextMessageimplement the Message interface.

In the above code we specify a typeequal to TEXT_MESSAGE and cast the returned instance appropriately.OPTIONAL J2ME APIS IN THE JTWI191Now that we have a TextMessage object we use the followingmethod to set the message text:public void setPayloadText(String data)We are now ready to send the message. This is achieved by invokingthe send method of the MessageConnection class:public void send(Message msg)Finally, when we no longer need the connection we should close itusing the close() method inherited from the Connection class.3.4.4.3 Receiving MessagesReceiving a message is, again, straightforward and is illustrated with thecode paragraph below.MessageConnection smsconn = null;Message msg = null;String receivedMessage = null;String senderAddress = null;try {conn = (MessageConnection) Connector.open(("sms://:1234”);msg = smsconn.receive();...//get sender's address for replyingsenderAddress = msg.getAddress();if (msg instanceof TextMessage) {//extract text messagereceivedMessage = ((TextMessage)msg).getPayloadText();//do something with message...}}catch (IOException ioe) {ioe.printStackTrace();}We open a server mode MessageConnection by passing in a URLof the following syntax:sms://:1234We retrieve the message by invoking the following method on theMessageConnection instance.public Message receive()The address of the message sender can be obtained using the followingmethod of the Message interface:public String getAddress()192MIDP 2.0 AND THE JTWIA server mode connection can be used to reply to incoming messages,by making use of the setAddress() method of the Message interface.In the case of a text message, we cast the Message object appropriatelyand then retrieve its contents with the TextMessage interface, using themethod below.public String getPayloadText()If the Message is an instance of BinaryMessage then the corresponding getPayloadData() method returns a byte array.In practice, of course, we need the receiving application to listenfor incoming messages and then invoke the receive() method uponreceipt.

We achieve this by implementing a MessageListener interface for notification of incoming messages. The MessageListenermandates one method, below, which is called on registered listeners bythe system when an incoming message arrives.public void notifyIncomingMessage(MessageConnection conn)The MessageConnection interface supplies the following to registera listener on MessageConnection:public void setMessageListener(MessageListener l)Only one listener can be registered on a given MessageConnection at a given time. A call to setMessageListener(l) will replacea previously registered MessageListener with l. To de-register aMessageListener on a MessageConnection we call setMessageListener(null).Note that the notifyIncomingMessage() method must returnquickly to avoid blocking the event dispatcher.

The method shouldnot, therefore, handle the incoming message directly but hand off theprocessing to a new thread.3.4.4.4 WMA in MIDP 2.0The Wireless Messaging API can be implemented on either MIDP 1.0or MIDP 2.0 platforms. When implemented in conjunction with MIDP2.0, the Wireless Messaging API can take advantage of the push registrytechnology. A MIDlet suite lists the server connections it wishes to registerin its JAD file, or manifest, by specifying the protocol and port for theconnection end point.

The entry has the following format:MIDlet-Push-<n>: <ConnectionURL>, <MIDletClassName>, <AllowedSender>OPTIONAL J2ME APIS IN THE JTWI193In this example, the entry in the JAD file would be as follows:MIDlet-Push-1: sms://:1234, SMSMIDlet, *The <AllowedSender> field acts as a filter indicating that the AMSshould only respond to incoming connections from a specific sender.

Forthe SMS protocol the <AllowedSender> entry is the phone number ofthe required sender (note the sender port number is not included in thefilter). Here the wildcard character ‘‘*’’ indicates respond to any sender.The AMS will respond to an incoming SMS directed to the specified MessageConnection by launching the corresponding MIDlet(assuming it is not already running). The MIDlet should then respondby immediately handling the incoming message in the startApp()method. As before, the message should be processed in a separate threadto avoid conflicts between blocking I/O operations and the normal userinteraction events.3.4.4.5 The SMS ChatMIDlet Sample CodeWe shall illustrate the WMA APIs just discussed using a simple SMSChatMIDlet.

The ChatMIDlet allows a user to send and receive SMSmessages and displays the ongoing conversation in a TextBox. TheChatMIDlet also makes use of the push registry so that the MIDlet willbe launched in response to an incoming SMS targeted at the application.Let’s first consider the main controller ChatMIDlet class.package com.symbian.devnet.chatmidlet;import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import javax.wireless.messaging.*;import javax.microedition.io.*;import java.io.*;public class ChatMIDlet extends MIDlet implements CommandListener,MessageListener{private Sender sender;private Receiver receiver;private MessageConnection smsconn;//Widgets for the UI for entering and reading the msgsprivate ChatView chatBox;private MessageView messageView;private Display display;private String smsPort;//The port on which we send SMS messagesprivate final static int SENT = 1;private final static int RECEIVED = 2;private final static int ERROR = 3;public ChatMIDlet() {display = Display.getDisplay(this);194MIDP 2.0 AND THE JTWIsmsPort = getAppProperty("SMS-Port");receiver = new Receiver(this);sender = new Sender(smsPort);chatBox = new ChatView(this);messageView = new MessageView(this);}public void startApp() {smsconn = receiver.open(smsPort);if (smsconn != null) {String[] connections =PushRegistry.listConnections(true);if (connections.length > 0) {for(int i = 0; i < connections.length; i++) {if (connections[i].equals("sms://:" + smsPort)) {receiver.handleMessage(smsconn);}}}display.setCurrent(chatBox);}else {//handle}}public void notifyIncomingMessage(MessageConnection conn) {if (conn == smsconn) {receiver.handleMessage(conn);}}public void pauseApp() {if (smsconn != null) {receiver.close(smsconn);smsconn = null; // make eligible for garbage collection}}public void destroyApp(boolean unconditional) {if (smsconn != null) {receiver.close(smsconn);}}public void commandAction(Command command,Displayable displayable) {if(command.getLabel().equals("Send")) {display.setCurrent(messageView);}else if(command.getLabel().equals("Exit")) {if (smsconn != null) {receiver.close(smsconn);}notifyDestroyed();}else if(command.getLabel().equals("OK")) {String message = messageView.getMessage();String phoneNumber = messageView.getPhoneNumber();sender.connectAndSend(message, phoneNumber);chatBox.addMsg(ChatMIDlet.SENT, message);display.setCurrent(chatBox);OPTIONAL J2ME APIS IN THE JTWI195}}public Display getDisplay() {return display;}public void msgTypeError(String error) {chatBox.addMsg(ChatMIDlet.ERROR,error);}public void processMsg(String message, String destinationAddress) {chatBox.addMsg(ChatMIDlet.RECEIVED,message);messageView.setPhoneNumber(destinationAddress);}}The ChatMIDlet constructor creates instances of the Sender andReceiver classes which encapsulate functionality for sending andreceiving SMS messages, and the ChatView and MessageView UIclasses.

The startApp() method sets up the Receiver for handlingincoming SMS messages by calling open() on the Receiver instance:public void startApp() {smsconn = receiver.open(smsPort);if (smsconn != null) {String[] connections = PushRegistry.listConnections(true);if (connections.length > 0) {for(int i = 0; i < connections.length; i++) {if (connections[i].equals("sms://:" + smsPort)) {receiver.handleMessage(smsconn);}}}display.setCurrent(chatBox);}else {//handle}}As will be shown later, in addition to opening a connection, thisalso registers the ChatMIDlet as a MessageListener on the receiverconnection.

The startApp() method also checks to see if it wasinvoked in response to an incoming message via the push registry and, ifso, immediately handles the message.Since the ChatMidlet class implements the MessageListenerinterface it must implement the notifyIncomingMessage interface:public void notifyIncomingMessage(MessageConnection conn) {if (conn == smsconn) {receiver.handleMessage(conn);}}196MIDP 2.0 AND THE JTWIThis checks that the incoming connection bearing the SMS messagebelongs to this application and if so calls the handleMessage() methodof Receiver to process the message in a separate Thread.The pauseApp() method, in line with good practice, releasesresources by closing the Receiver.Now let’s look at the Receiver class:package com.symbian.devnet.chatmidlet;import javax.wireless.messaging.*;import java.io.*;import javax.microedition.io.*;// Opens and closes a connection for receiving SMS messages.public class Receiver implements Runnable {privateprivateprivateprivateChatMIDlet chat;MessageConnection smsconn;boolean listening = false;int messageWaiting = 0;public Receiver(ChatMIDlet chat) {this.chat = chat;}public MessageConnection open(String smsPort) {String smsAddress = "sms://:" + smsPort;MessageConnection conn = null;try {conn = (MessageConnection) Connector.open(smsAddress);conn.setMessageListener(chat);receiverThread.start();listening = true;}catch (IOException ioe) {ioe.printStackTrace();}return conn;}public synchronized void handleMessage(MessageConnection conn) {messageWaiting++;smsconn = conn;notify();}public void run() {while (listening) {synchronized(this) {while (listening && messageWaiting == 0 ) {try {wait();} catch (InterruptedException ie) {// Handle interruption}}if (messageWaiting != 0) {receiveMessage();messageWaiting--;}}OPTIONAL J2ME APIS IN THE JTWI197}}public void receiveMessage() {Message msg = null;String senderAddress = null;String receivedMessage = null;try {msg = smsconn.receive();if (msg != null) {senderAddress = msg.getAddress();if (msg instanceof TextMessage) {receivedMessage =((TextMessage)msg).getPayloadText();chat.processMsg(receivedMessage, senderAddress)} else {chat.msgTypeError("Error whilst receiving.");}}} catch (IOException ioe) {ioe.printStackTrace();}}public synchronized void close(MessageConnection conn) {listening = false;notify();if (conn != null) {try {conn.setMessageListener(null);conn.close();}catch(IOException ioe) {ioe.printStackTrace();}}}}The open() method opens a message connection, registers a MessageListener (the ChatMIDlet instance) on this connection andstarts a new thread for handling incoming messages.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее