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

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

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

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

A DataElement can encapsulate data of the followingtypes by using one of the overloaded constructors of the DataElement class:• UUID• String• integer• boolean• sequences of any one of the above types.Another useful method of ServiceRecord is:public void setDeviceServiceClasses(int classes)This is used to set the major service class in the ServiceRecord ofthis service (e.g. rendering, audio, telephony, etc.). This information isused to create a DeviceClass object which encapsulates informationabout the types of service offered by this device and is used in deviceinquiry to find suitable devices (see Section 4.3.2).4.3.1.3 UUIDsUniversally Unique Identifiers (UUIDs) are 128-bit values that uniquelyidentify a Bluetooth service. For convenience the SDP allows the use of16-bit or 32-bit alias (‘‘short’’) UUIDs, with the Bluetooth specificationproviding an algorithm describing how a 16-bit or 32-bit alias can bepromoted to the actual 128-bit UUID for comparison.Every service, including generic low-level protocols and profiles, hasa UUID.

For regular protocols and profiles the UUIDs are pre-definedand, for convenience, are normally represented by their 16-bit (or 32-bit)aliases (see Assigned Numbers at www.bluetooth.org). Some of the 16-bitUUIDs for Bluetooth protocols and profiles are listed below.ProtocolL2CAPRFCOMMSDPOBEXProfileSerial PortBasic PrintingFaxUUID0x01000x00030x00010x0008UUID0x11010x11220x1111212JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYTo convert a 16-bit or 32-bit alias to the actual 128-bit UUID thefollowing prescription is used:128 bit value = 16 bit value * 296 + Bluetooth Base UUID128 bit value = 32 bit value * 296 + Bluetooth Base UUIDWhere the Bluetooth_Base_UUID has the value of:0x0000000000001000800000805F9B34FBHowever, Java developers do not have to worry about these conversionsas the Java APIs for Bluetooth provide the javax.bluetooth.UUID classto create and manipulate UUIDs.

To create an actual (long) 128-bit UUIDwe use the following constructor.public UUID(long uuidValue)The constructor takes a 16-bit or 32-bit alias as the uuidValueargument and returns a UUID instance representing the 128-bit value.We can also create UUID instances from a String representing a16-bit or 32-bit alias using an alternative constructor:public UUID(String uuidValue, boolean shortUUID)If shortUUID is true, the constructor will create an instance representing a 16- or 32-bit UUID depending on the length of the Stringrepresentation of the UUID alias passed in as uuidValue (i.e.

fourcharacters for a 16-bit alias or eight characters for a 32-bit alias). IfshortUUID is false then a 128-bit UUID will be returned, provideda 32 character String representation of a 128-bit value was passed inas uuidValue.4.3.1.4 Creating the ServerHaving introduced some of the concepts and classes necessary for registering a server, we shall now have a look at how this is realized in codeusing the APIs. The code for setting up a simple server to accept streamconnections using the Serial Port profile is shown below.private static final String uuidString ="00112233445566778899AABBCCDDEEFF";...UUID uuid = new uuid(uuidString, false);...try {LocaDevice device = LocalDevice.getLocalDevice();PROGRAMMING THE BLUETOOTH APIs213//make generally discoverabledevice.setDiscoverable(DiscoveryAgent.GIAC);StreamConnectionNotifier service = (StreamConnectionNotifier)Connector.open("btspp://localhost:" +uuid.toString() + ";name=serialconn");StreamConnection conn = service.acceptAndOpen();InputStream input = conn.openInputStream();...input.close();conn.close();} catch(BluetoothStateException bse) {bse.printStackTrace();}catch(InputOutputException ioe){ioe.printStackTrace();}Let’s look at this code in more detail.

First, we create a UUID touniquely identify this service. Here we use a string representing a 128-bitUUID to create a UUID instance using the appropriate constructor:private final String uuidString = "00112233445566778899AABBCCDDEEFF";UUID uuid = new uuid(uuidString, false);Note that we pass in false as the second argument as we are creatinga long UUID.

Next we use the static factory method getLocalDevice()to obtain an instance of the LocalDevice representing the host device.LocaDevice device = LocalDevice.getLocalDevice();device.setDiscoverable(DiscoveryAgent.GIAC);We make the Bluetooth device discoverable using the setDiscoverable() method. The pre-defined public static final int GIACvalue represents a General/Unlimited Inquiry Access Code, meaning thereare no restrictions placed on which remote devices may discover the host.To establish an RFCOMM connection using the SPP we use theopen() method as follows:StreamConnectionNotifier service =(StreamConnectionNotifier)Connector.open("btspp://localhost:" +uuid.toString() + ";name=serialconn");The localhost identifier refers to the host device and is the RFCOMMserver channel identifier. This is added to the ServiceRecord as theProtocolDescriptorList attribute.

It is also necessary to appenda String representation of the UUID. This is added to the ServiceRecord in the ServiceClassIDList. An optional name forthe service can also be appended to the URL which is added to theServiceRecord as the ServiceName attribute.214JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYThe open() method returns an object of type StreamConnectionNotifier. Calling acceptAndOpen() on the StreamConnectionNotifier indicates the server is ready to accept client connectionsand adds the ServiceRecord to the SDDB.StreamConnection conn = service.acceptAndOpen();The acceptAndOpen() method blocks until the server accepts aconnection request, returning a StreamConnection object to enablecommunication between the client and server.4.3.2 Device DiscoveryIn the previous section, we saw how we can use the Java APIs to set upa server offering a Bluetooth service.

In the next few sections we shallsee how clients can locate and access this service. This is generally atwo-stage process involving discovering active Bluetooth devices in thevicinity, then searching discovered devices for the required service. Thissection deals with device discovery.Device discovery is in fact very simple. First we need to implement aDiscoveryListener. The javax.bluetooth.DiscoveryListener interface mandates the four callback methods shown below.publicpublicpublicpublicvoidvoidvoidvoiddeviceDiscovered(RemoteDevice btDevice, DeviceClass cod)inquiryCompleted(int discType)servicesDiscovered(int transID, ServiceRecord[] servRecord)serviceSearchCompleted(int transID, int respCode)To implement a device DiscoveryListener we need to providenon-trivial implementations for the first two methods.The deviceDiscovered() method is called by the implementationwhen a device is discovered.

It may be called many times. The implementation passes in a RemoteDevice instance representing the remotedevice just discovered and also a DeviceClass instance that providesinformation about the type of device just discovered, allowing filtering ofunwanted devices.The inquiryCompleted() method is called by the implementationwhen the device inquiry has completed.

discType can have one ofthree values predefined in the DiscoveryListener interface:• public static int INQUIRY_COMPLETED – which indicates thatthe inquiry terminated normally• public static int INQUIRY_TERMINATED – which indicatesthat the inquiry was terminated by the application (via the cancelInquiry() method of DiscoveryAgent)PROGRAMMING THE BLUETOOTH APIs215• public static int INQUIRY_ERROR – which indicates that theinquiry failed to complete normally, but was not terminated.To initiate a device inquiry we need to obtain a DiscoveryAgent usingthe getDiscoveryAgent() method of the LocalDevice and invokethe following method on it:public boolean startInquiry(int accessCode, DiscoveryListener listener)The startInquiry() method takes an appropriately implementedDiscoveryListener and also an accessCode that can have one oftwo values pre-defined in the DiscoveryAgent class.public static final GIACpublic static final LIACThe General/Unlimited Inquiry Access Code (GIAC) indicates anunlimited search returning all devices found in the vicinity.

Using theLimited Dedicated Inquiry Access Code (LIAC) discovers only remotedevices in LIAC mode. Both values are defined in the Bluetooth GAPspecification (www.bluetooth.org). Use GIAC for general inquiries.We shall illustrate the APIs just discussed with a concrete example:import java.io.*;import javax.bluetooth.*;import java.util.*;public class DeviceDiscoverer implements DiscoveryListener {private BluetoothUI btUI;public Vector remoteDevices = new Vector();private LocalDevice localDevice;private DiscoveryAgent agent;public DeviceDiscoverer(BluetoothUI btUI) {this.btUI = btUI;try {localDevice = LocalDevice.getLocalDevice();}catch(BluetoothStateException bse){ //handle}agent = localDevice.getDiscoveryAgent();}public void startDeviceSearch() {try {agent.startInquiry(DiscoveryAgent.GIAC, this);} catch(BluetoothStateException bse){ //handle}}public void servicesDiscovered(int transID, ServiceRecord[] servRecord){}public void serviceSearchCompleted(int transID, int respCode) {}216JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYpublic void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {// The major device class of 0x600 is an imaging deviceif ((cod.getMajorDeviceClass() == 0x600) {// The minor device class of 0x80 is a printerif ((cod.getMinorDeviceClass() & 0x80) != 0) {// The service class of 0x40000 is a rendering serviceif ((cod.getServiceClasses() & 0x40000) != 0) {remoteDevices.addElement(btDevice);}}}}public void inquiryCompleted(int discType) {if(discType == DiscoveryListener.INQUIRY_COMPLETED) {btUI.displayDevices(remoteDevices);}else{//take appropriate action}}}Our DeviceDiscoverer class implements the DiscoveryListener interface.

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

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

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

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