quick_recipes (779892), страница 54

Файл №779892 quick_recipes (Symbian Books) 54 страницаquick_recipes (779892) страница 542018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

For detailed information, please refer to theclass reference in the Symbian Developer Library documentation (the‘Location Acquisition API’ section).There are various privacy and potential legal issues in being able todetermine where someone is. On a mobile device, it is a concern that auser will unwittingly enable other people to discover their whereabouts.It is also an anxiety that a malicious application will transmit its locationto a remote party. Appropriate security and privacy mechanisms shouldbe implemented to give the user confidence that their location is secure.The Location platform security capability is required by the examplesgiven with these recipes. The user can authorize individual requests todetermine the location of the smartphone as they arrive from the network.TestingYou can test the LBS recipes and your own LBS-related code on eitherthe emulator or on a device. The S60 emulator usually has built-inGPS support, so you can run and debug your code directly in IDE.302SYMBIAN C++ RECIPESFor the simple cases, you do not need to do any further configuration.The device manufacturer may provide some GPS simulation tools toallow the developers to test their code in more complicated scenarios.

For instance, Nokia has introduced a Positioning Simulation Toolavailable in the S60 3rd Edition SDK that you can use on the emulatorand on the phones without GPS hardware or GPS accessories available. You can find more details about using and configuring this toolon the emulator and the phone under ‘Tools Collection for LocationBased Application Development’ section of the S60 3rd Edition SDKdocumentation. A description of the usage of these simulation toolswith Nokia’s free Remote Device Access service can be found atwiki.forum.nokia.com/index.php/Using positioning simulation toolwith RDA and a set of documentation provided by Forum Nokia is available at www.forum.nokia.com/main/resources/technologies/locationbased services.html.At the time of going to press, UIQ does not provide such support forGPS simulations, but you can reuse any generic Symbian OS LBS code,tested on S60, on the UIQ platform.4.10.1 Easy Recipes4.10.1.1Get the List of Available Positioning Technology ModulesAmount of time required: 20 minutesLocation of example code: \LocationRequired library(s): lbs.lib (S60), lbsselflocate.lib (UIQ)Required header file(s): lbs.hRequired platform security capability(s): LocationProblem: You want to list positioning technology modules available onthe handset.Solution: A positioning technology module is a low-level software component that allows the location server to communicate with the mobiledevice hardware that obtains position data.

When a client applicationor remote party makes a request for new location information, a modulemust be used to service the request. The LBS API allows applications todiscover the positioning technology modules available to it. Applicationscan make a choice of the specific positioning technology module to useto get the device’s location.

This module choice can be made in threeways:• The client application chooses a particular module to use for locationinformation requests and specifies this choice to the location serverpassing module ID in the RPositioner::Open() call. This methodreturns KErrNotFound if the specified module ID does not exist.LOCATION-BASED SERVICES303This recipe illustrates how to obtain the list of available technologymodules.• The application specifies a set of position quality criteria to the location server passing the appropriate parameter to RPositioner::Open().

When the application makes a location information request,the server chooses the module that best satisfies the quality criteria.Position quality criteria are discussed in the next recipe.• The application does not specify a particular module or any location quality criteria, so the location server uses the default moduleto obtain the location information, as specified by RPositionServer::GetDefaultModuleId().The code snippet below demonstrates how to request the list of available modules and filter them according to desired type and capabilities:#include <lbs.h>TInt GetModuleIdsL(RArray<TPositionModuleId>& aModuleIds,TPositionModuleInfo::TTechnologyType aType,TPositionModuleInfo::TCapabilities aCaps){RPositionServer server;TUint numModules;TPositionModuleId modId;TPositionModuleInfo modInfo;TPositionModuleStatus modStatus;aModuleIds.Reset();// 1.

Create a session with the location serverUser::LeaveIfError(server.Connect());CleanupClosePushL(server);// 2. Get the number of modules installedUser::LeaveIfError(server.GetNumModules(numModules));// 3. Iterate over the modules to get information about//each module// 4. Get the availability of a module// 5. Get information about the module technology, quality etc.for (TUint i=0; i<numModules; i++){User::LeaveIfError(server.GetModuleInfoByIndex(i, modInfo));// Check module technology type and availabilityif ( modInfo.IsAvailable() &&(modInfo.TechnologyType() == aType) ){// Check module capabilitiesTPositionModuleInfo::TCapabilities caps =modInfo.Capabilities();304SYMBIAN C++ RECIPESif (caps & aCaps == aCaps){// Check module position qualityTPositionQuality quality;modInfo.GetPositionQuality(quality);// In this example, check for horizontal// accuracy better than 10 metresif (!Math::IsNaN(quality.HorizontalAccuracy()) &&quality.HorizontalAccuracy() < 10 ){// This module has all the required characteristics!modId = modInfo.ModuleId();aModuleIds.AppendL(modId);}}}}// 6.

Close the location server sessionCleanupStack::PopAndDestroy(&server);return aModuleIds.Count();}4.10.1.2Retrieve the Current Module Status InformationAmount of time required: 15 minutesLocation of example code: \LocationRequired library(s): lbs.lib (S60), lbsselflocate.lib (UIQ)Required header file(s): lbs.hRequired platform security capability(s): LocationProblem: You want to retrieve the current positioning module statusinformation.Solution: A positioning module has a status defined in TPositionModuleStatus object. The status describes the low-level state of a module,such as whether it is disabled, initializing or ready to retrieve locationdata, as well as its data quality status. You can also receive notificationwhen the status changes, as the next recipe demonstrates.The module status can be obtained by calling TPositionModuleStatusEvent::GetModuleStatus() and providing a TPositionModuleStatus reference as parameter. The latter class has the methodsto return device and data quality information, respectively.The following sample describes how to obtain the current module stateinformation:#include <lbs.h>TPositionModuleStatus modStatus;// Assume that the app has established the session with// the location server and gathered the module Id for which itLOCATION-BASED SERVICES305// wants status.

Get the module status.User::LeaveIfError(server.GetModuleStatus(modStatus, modId));// Use the statusTPositionModuleStatus::TDeviceStatus deviceStatus =modStatus.DeviceStatus();TPositionModuleStatus::TDataQualityStatus qualityStatus =modStatus.DataQualityStatus();// Can check the status of the module device - for example// check for device errorif (deviceStatus == TPositionModuleStatus::EDeviceError){// Device error for this module}// Can check the data quality for the module - for example check for// loss of data qualityif (qualityStatus == TPositionModuleStatus::EDataQualityLoss){// Loss of quality for this module}// Don’t forget to close the location server session!4.10.1.3Receive Module Status Change NotificationsAmount of time required: 20 minutesLocation of example code: \LocationRequired library(s): lbs.lib (S60), lbsselflocate.lib(UIQ)Required header file(s): lbs.hRequired platform security capability(s): LocationProblem: You want to receive notifications about positioning modulestatus changes.Solution: A change in module status is indicated by a status event.

Detailsof the event are held in a TPositionModuleStatusEvent object.Client applications can receive notification of status events from thelocation server.There are three types of module status events:• Data quality status events.• Device status events.• System-level events, which indicate that a module has been added orremoved in the system.Quality status events are useful for applications that need to modifytheir behavior based on the quality of location information that can bereceived.

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

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

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

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