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

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

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

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

In the run() method, welaunch the server in a new Thread listening for incoming connections.When a remote device connects to the service an InputStream isopened to read the data, then an Image is constructed from the dataand displayed.The classes that make up the BT Demo Client MIDlet are depicted inFigure 4.8.The BTDemoClient class is listed below and acts as the controller forthe client MIDlet.importimportimportimportimportpublicjavax.microedition.midlet.*;javax.microedition.lcdui.*;javax.microedition.io.*;javax.bluetooth.*;java.io.*;class BTDemoClient extends MIDlet implements CommandListener {private static final String IMAGE_NAME = "/image.png";private static final int IMAGE_SIZE = 11222;private byte[] imageData;private Display display;private Command exitCommand = new Command("Exit", Command.EXIT, 1);private Command startCommand = new Command("Start", Command.SCREEN,1);private Command sendCommand = new Command("Send", Command.SCREEN, 1);234JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYprivate ImageCanvas imageCanvas;private BluetoothUI btUI;privateprivateprivateprivateprivateDeviceDiscoverer deviceDiscoverer;ServiceDiscoverer serviceDiscoverer;RemoteDevice[] remoteDevices;ServiceRecord serviceRecord;StreamConnection conn;public BTDemoClient() {display = Display.getDisplay(this);imageData = loadImage(IMAGE_NAME, IMAGE_SIZE);Image image = Image.createImage(imageData, 0, imageData.length);imageCanvas = new ImageCanvas(image);imageCanvas.addCommand(startCommand);imageCanvas.setCommandListener(this);btUI = new BluetoothUI();deviceDiscoverer = new DeviceDiscoverer(this);serviceDiscoverer = new ServiceDiscoverer(this);}public byte[] loadImage(String imageName, int imageSize) {byte[] data = new byte[imageSize];try {Class c = this.getClass() ;InputStream is = c.getResourceAsStream(imageName);DataInputStream dis = new DataInputStream(is);dis.readFully(data);is.close();}catch(IOException ioe) {btUI.setStatus("IOException: " + ioe.toString());}return data;}public void startServiceSearch(int index) {btUI.setStatus("Starting service search");serviceDiscoverer.startServiceSearch(remoteDevices[index]);}//Called from ServiceDiscoverer.serviceSearchCompleted// when service search is complete.public void searchCompleted(ServiceRecord servRecord,String message) {this.serviceRecord = servRecord;//cache the service record for future usebtUI.setStatus(message);new Thread() {public void run() {sendImage(serviceRecord);}}.start();}//Called from ServiceDiscoverer.inqiryCompleted// when device inquiry is complete.public void inquiryCompleted(RemoteDevice[] devices, String message) {SAMPLE CODE235this.remoteDevices = devices;String[] names = new String[devices.length];for(int i = 0; i < devices.length; i++) {try {String name = devices[i].getFriendlyName(false);names[i] = name;}catch(IOException ioe){btUI.setStatus("IOException: " + ioe.toString());}}btUI.populateList(names);btUI.addCommand(sendCommand);btUI.setStatus(message);}public void sendImage(ServiceRecord serviceRecord) {try {String url =serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);conn = (StreamConnection)Connector.open(url);DataOutputStream dataOutputStream =conn.openDataOutputStream();btUI.setStatus("connected");dataOutputStream.write(imageData);dataOutputStream.flush();dataOutputStream.close();DataInputStream dataInputStream = conn.openDataInputStream();int eof = dataInputStream.readInt();if(eof == -1) {dataInputStream.close();conn.close();conn = null;btUI.setStatus("closed connection");}} catch(IOException ioe) {btUI.setStatus("IOException: " + ioe.toString());}}public void commandAction(Command c, Displayable d) {if (c == exitCommand) {destroyApp(true);notifyDestroyed();} else if (c == startCommand) {imageCanvas.removeCommand(exitCommand);imageCanvas.removeCommand(startCommand);imageCanvas.setCommandListener(null);btUI.addCommand(exitCommand);btUI.setCommandListener(this);display.setCurrent(btUI);deviceDiscoverer.startDeviceSearch();btUI.setStatus("Searching for Bluetooth devices");} else if (c == sendCommand) {236JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYint index = btUI.getSelectedDevice();startServiceSearch(index);btUI.removeCommand(sendCommand);}}public void startApp() {display.setCurrent(imageCanvas);}public void destroyApp(boolean unconditionally) {try {if(conn != null)conn.close();}catch(IOException ioe) {btUI.setStatus("IOException: " + ioe.toString());}}public void pauseApp() {}}The class creates the Image from a resource file and displays it in aCanvas.

Selecting the Start command starts a device inquiry using theDeviceDiscoverer class, listed below.import javax.bluetooth.*;import java.util.*;public class DeviceDiscoverer implements DiscoveryListener {private BTDemoClient btClient;private Vector remoteDevices = new Vector();private DiscoveryAgent agent;public DeviceDiscoverer(BTDemoClient btClient) {this.btClient = btClient;try {LocalDevice localDevice = LocalDevice.getLocalDevice();agent = localDevice.getDiscoveryAgent();}catch(BluetoothStateException bse) {bse.printStackTrace();}}public void startDeviceSearch() {try {agent.startInquiry(DiscoveryAgent.GIAC, this); //non-blocking}catch(BluetoothStateException bse){bse.printStackTrace();}}SAMPLE CODE237public void servicesDiscovered(int transID,ServiceRecord[] servRecord){}public void serviceSearchCompleted(int transID, int respCode) {}public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {// The minor device class of 0x40000 is a rendering serviceif ((cod.getServiceClasses() & 0x40000) != 0)remoteDevices.addElement(btDevice);}public void inquiryCompleted(int discType) {String message = null;RemoteDevice[] devices = null;if (discType == INQUIRY_COMPLETED) {message = "Inquiry completed";devices = new RemoteDevice[remoteDevices.size()];for(int i = 0; i < remoteDevices.size(); i++) {devices[i] = (RemoteDevice)remoteDevices.elementAt(i);}} else if (discType == INQUIRY_TERMINATED) {message = "Inquiry terminated";} else if (discType == INQUIRY_ERROR) {message = "Inquiry error";}btClient.inquiryCompleted(devices, message);}}The deviceDiscovered() method filters the device inquiry fordevices of the Rendering major service class.When the inquiry is completed the system invokes the inquiryCompleted() method mandated by the DiscoveryListener Interface.This returns control to the BTDemoClient instance by calling itsinquiryCompleted() method, passing back an array of RemoteDevices and a message indicating the success (or otherwise) of the inquiry.The BTDemoClient class then instigates a service search using theServiceDiscoverer class, listed below, which also implements theDiscoveryListener Interface.import javax.bluetooth.*;import java.io.*;public class ServiceDiscoverer implements DiscoveryListener {private static final UUID[] uuidSet ={new UUID("00112233445566778899AABBCCDDEEFF", false)};private static final String SERVICE_NAME = "serialconn";//return service name attributeprivate static final int[] attrSet = {0x0100};private BTDemoClient btClient;238JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYprivate ServiceRecord serviceRecord;private String message;private DiscoveryAgent agent;public ServiceDiscoverer(BTDemoClient btClient) {this.btClient = btClient;try {LocalDevice localDevice = LocalDevice.getLocalDevice();agent = localDevice.getDiscoveryAgent();}catch(BluetoothStateException bse) {bse.printStackTrace();}}public void startServiceSearch(RemoteDevice remoteDevice) {try {String device = remoteDevice.getFriendlyName(true);}catch(IOException ioe) {ioe.printStackTrace();}try {//non-blockingagent.searchServices(attrSet, uuidSet, remoteDevice, this);} catch(BluetoothStateException bse) {bse.printStackTrace();}}public void servicesDiscovered(int transID,ServiceRecord[] servRecord) {for(int i = 0; i < servRecord.length; i++) {DataElement serviceNameElement =servRecord[i].getAttributeValue(0x0100);//get the Service NameString serviceName = (String)serviceNameElement.getValue();if(serviceName.equals(SERVICE_NAME)){serviceRecord = servRecord[i];}}}public void serviceSearchCompleted(int transID, int respCode) {if (respCode ==DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE) {message = "Device not reachable";}else if(respCode == DiscoveryListener.SERVICE_SEARCH_NO_RECORDS) {message = "Service not available";}else if (respCode == DiscoveryListener.SERVICE_SEARCH_COMPLETED) {message = "Service search completed";}SAMPLE CODE239else if(respCode == DiscoveryListener.SERVICE_SEARCH_TERMINATED) {message = "Service search terminated";}else if (respCode == DiscoveryListener.SERVICE_SEARCH_ERROR) {message = "Service search error";}btClient.searchCompleted(serviceRecord, message);}public void inquiryCompleted(int discType){}public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod){}}When we call the following method to start the service search:agent.searchServices(attrSet, uuidSet, remoteDevice, this);we specify a non-null attrSet argument:private static final int[] attrSet = {0x0100};The value 0x0100 indicates the service name attribute (in the primarylanguage) so this attribute will be retrieved from discovered servicerecords in addition to the default attribute list.

The system invokes theservicesDiscovered() method when a service is discovered. Wefilter the discovered services to find the one with name ‘‘serialconn’’which is then cached.When the service search is completed the system invokes the serviceSearchCompleted() method mandated by the DiscoveryListener Interface. This returns control to the BTDemoClient instance bycalling its searchCompleted() method, passing back the cachedServiceRecord and a message reporting the success of the search.The BTDemoClient can then use the discovered ServiceRecordto open a connection to the SPP server service using the sendImage() method:public void sendImage(ServiceRecord serviceRecord) {try {String url = serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);conn = (StreamConnection)Connector.open(url);DataOutputStream dataOutputStream = conn.openDataOutputStream();btUI.setStatus("connected");dataOutputStream.write(imageData);dataOutputStream.flush();dataOutputStream.close();240JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYDataInputStream dataInputStream = conn.openDataInputStream();int eof = dataInputStream.readInt();if(eof == -1) {dataInputStream.close();conn.close();conn = null;btUI.setStatus("closed connection");}} catch(IOException ioe) {btUI.setStatus("IOException: " + ioe.toString());}}Figure 4.9 shows screenshots from the sample application.The full source code and JAR and JAD files for the BT Demo Server andBT Demo Client MIDlets can be downloaded from the Symbian websiteat www.symbian.com/books.a.

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

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

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

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