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

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

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

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

Bluetooth is designed for connecting small, battery-powered devices at ranges of up to 10 m and at a datatransfer rate of 1 Mb/s. By comparison with 802.11b (WiFi) technology,which also operates in the 2.4 GHZ band, Bluetooth has a shorter range(10 m compared to 100 m), lower data transfer rates (1 Mb/s comparedto 10 Mb/s), but consumes much less power, making it a more suitabletechnology for battery-powered devices.Symbian OS has provided native support for Bluetooth since SymbianOS Version 6.1.Programming Java 2 Micro Edition on Symbian OS: A developer’s guide to MIDP 2.0. Martin de Jode 2004 Symbian Ltd ISBN: 0-470-09223-8206JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGY4.2 Introduction to the Bluetooth APIsThe aim of JSR 82 was to provide a standard set of Java APIs to allowJava-enabled devices to integrate into a Bluetooth environment.

The JSR82 expert group was formed in November 2000, with Symbian a member,and produced a final release of the specification in March 2002.The Bluetooth specification created and released by the Bluetooth SIGruns to more than 1500 pages and continues to grow as new profiles areadded. It covers many layers and profiles and it is not the intention of JSR82 to include them all. Rather, the Java API implements a core subset ofthe Bluetooth specification providing support for generic profiles (e.g. theSerial Port profile). It is the general intention that higher-level Bluetoothprofiles can be built on top of this API using Java.4.2.1 Bluetooth Protocol StackFor a device to support Bluetooth, naturally it must provide both the necessary hardware support (an RF transmitter, etc.) and the necessary softwaresupport to implement the Bluetooth protocol and control the Bluetoothhardware programmatically.

This software is known as the Bluetoothprotocol stack. The Bluetooth protocol stack is directly analogous withother familiar communication protocol stacks, such as HTTP or WAP.Figure 4.1 shows a simplified diagram of the Bluetooth protocol stack.UDP/TCPIPOBEXPPPRFCOMMSDPL2CAPHost Controller InterfaceFigure 4.1The Bluetooth protocol stack.INTRODUCTION TO THE BLUETOOTH APIs207Some of the protocols are specific to Bluetooth, such as the Logical LinkControl and Adaptation Protocol (L2CAP); others are adopted protocols,such as OBEX, PPP, IP, UDP and TCP. The Host Controller Interface(HCI) is the interface between software and hardware.

Everything belowthe HCI is implemented in hardware, everything above is implementedin software.L2CAP is the lowest protocol of the Bluetooth stack and it handles alldata transmission from the upper layers. It is responsible for segmentingdata into packets for transmission and re-assembling received data packets. The RFCOMM layer simulates the functionality of a standard serialcommunication port and is a cable replacement protocol.

The service discovery protocol (SDP) is used for discovering Bluetooth services offeredby remote devices.4.2.2 ProfilesProfiles are defined by the Bluetooth SIG to enable Bluetooth devicesto interoperate. Each profile specifies a set of functionality to achieve aparticular task. It goes onto to define how this functionality is implementedusing the layers of the protocol stack. Profiles range from low-level genericprofiles, such as the Generic Access profile which is used by all otherprofiles for basic establishment of connections, to highly specific highlevel profiles, such as the Headset profile, designed to enable Bluetoothdevices to connect to cordless Bluetooth-enabled headsets.Since there are hundreds of Bluetooth profiles, with new ones beingadded all the time, it was not the intention of the expert group for JSR 82 toattempt to provide support directly for high-level profiles.

It supports onlythe generic profiles, which can then be used to implement higher-levelprofiles in Java.4.2.3 Requirements of JSR 82JSR 82 is an optional API targeted at J2ME devices. More specifically, it isaimed at any device that supports the Connected Limited Device Configuration (CLDC, see Chapter 1) and the Generic Connection Framework(or a superset of them, such as the CDC).To implement the Java APIs for Bluetooth Wireless Technology, theunderlying Bluetooth system must support the following layers andgeneric profiles in the Bluetooth stack:• L2CAP• RFCOMM• SDP• Service Discovery Application Profile• Serial Port profile.208JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYThe specification for JSR 82 also requires that the system supply anebulous entity known as the Bluetooth Control Center (BCC).

The BCCis a ‘‘Control Panel’’-like application that provides various functionsamongst which are configuration options including allowing the user tospecify security settings for Bluetooth connections as well as maintaininga list of known devices. On Symbian OS the BCC functionality is alreadyprovided by the underlying native Bluetooth system.The current specification of JSR 82 was targeted at Version 1.1 of theBluetooth specification as defined by the Bluetooth SIG. The intention is,however, that JSR 82 should be interoperable with stacks or hardwarebased on earlier or subsequent versions of the Bluetooth specification.4.2.4 The Java Bluetooth PackagesJSR 82 specifies two packages:• javax.obex• javax.bluetooth.The Object Exchange Protocol (OBEX) is a communication protocoloriginally defined by the Infrared Data Association (IrDA) that has beenadopted by the Bluetooth SIG.

Since OBEX is an independent protocol,it is supplied in a separate package. Applications may use the OBEX APIindependently of the Bluetooth API.The Java Bluetooth API is intended to provide support for the followingcapabilities:• registering services• discovering devices and services• establishing connections using RFCOMM, L2CAP and OBEX• providing support for secure connections.Symbian’s current implementation of JSR 82 does not provide an implementation of the OBEX API and hence it does not have a javax.obexpackage.4.3 Programming the Bluetooth APIs4.3.1 Service Registration4.3.1.1 Basic StepsWhen we, as users, make a Bluetooth connection to a remote device toperform some task such as sending a file, what we are in fact doing isPROGRAMMING THE BLUETOOTH APIs209accessing a service offered by the remote device.

To someone new toBluetooth it is not immediately obvious that making Bluetooth connections is ultimately about connecting to services rather than devices. Beforea Bluetooth host device can communicate with a remote Bluetooth peer,a service must be registered and offered by the remote device.As application developers wishing to register a service, we need toperform the following steps:• create a service record• add a service record to the server’s Service Discovery Database• set security measures associated with connections to clients• accept connections from clients that request service.4.3.1.2 Service RecordsThe Service Discovery Database (SDDB) maintains a repository of servicerecords corresponding to the services offered by the host device.

A servicerecord provides sufficient information to allow a client to connect to theBluetooth service being offered by the server. Service discovery is theprovince of the Service Discovery Application Protocol (SDAP) whichitself uses the Service Discovery Protocol layer in the Bluetooth stack.The APIs for creating a service record and adding it to the SDDB are Javawrappers around functionality defined in the SDAP and SDP.The Java APIs provide an abstraction of the Bluetooth Service Record in the javax.bluetooth.ServiceRecord interface.

A ServiceRecord contains information about the service in a set of attributesin the form of (ID, value) pairs, where the ID is a 16-bit unsigned integer,and the value is an instance of a javax.bluetooth.DataElement.A ServiceRecord may contain many attributes to fully describe theservice being offered. However, only two attributes are required to bepresent in a ServiceRecord, the ServiceRecordHandle and theServiceClassIDList.Some key attributes contained in a ServiceRecord:Attribute NameServiceRecordHandleServiceClassIDListServiceRecordStateServiceIDAttribute IDAttribute Value Type0x00000x00010x00020x000332-bit unsigned integerSequence of UUIDs32-bit unsigned integerUUIDEach Bluetooth device offering a service represents an instance of anSDP server.

The ServiceRecordHandle identifies this ServiceRecord within the current instance of an SDP server. Otherwise identical210JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYservice records running in different SDP instances will have different valuesfor the ServiceRecordHandle.The ServiceClassIDList is a list of UUIDs that represent the typeof service being offered. For instance, a printing service being offered viathe Serial Port profile may contain the following (16-bit) UUIDs: 0x11019Serial Port and 0x1121 Basic Printing. The ServiceClassIDList mustcontain at least one service class UUID.

We will discuss UUIDs in moredetail in the next section.The ServiceRecordState is used by the SDP server to maintaina cache of service attributes. The value of the ServiceRecordStateattribute will change every time an attribute is added, deleted or changedwithin the service record.The ServiceID is a UUID that uniquely and universally identifies theservice instance being described by this record. It is particularly useful ifthe same service is offered by many SDP servers, but a particular instanceneeds to be identified.Other useful attributes include:Mnemonic for String IDServiceNameServiceDescriptionProviderNameAttribute ID (relative)0x00000x00010x0002These attribute ID values must be added to the base offset (given by theLanguageBaseAttributeIDList with attribute ID 0x0006) whichhas the value of 0x0100 for the primary language.For more information on service attributes refer to the Java Bluetooth API documentation or the SDP specification at the Bluetooth SIG(www.bluetooth.org).The Java API provides methods in the ServiceRecord interface toset and retrieve attribute values.public DataElement getAttributeValue(int attrID)public boolean setAttributeValue(int attrID, DataElement attrValue)The getAttributeValue() method returns the attribute specified by the attrID in the form of a DataElement.

The setAttributeValue() method sets an attribute specified by attrID with avalue represented by the DataElement, attrValue. To update a ServiceRecord already added in the SDDB we use the updateRecord()method of LocalDevice. Otherwise the ServiceRecord will beupdated when we first add it to the SDDB (when acceptAndOpen() iscalled, see Section 4.3.1.4).PROGRAMMING THE BLUETOOTH APIs211All attributes are stored in the ServiceRecord in the form of aDataElement.

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

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

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

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