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

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

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

For example, an application may need to show a message whena user moves into an area where the accuracy of location information is306SYMBIAN C++ RECIPESdegraded to a lower quality than is required because of distance from abase station or inability to receive satellite signals.Device status events and system module events are most useful tosoftware components that perform administrative operations, such astaking a positioning module online or offline. The events can be used tonotify when such an administrative operation is complete.Device status events can also be used to keep a user informed as tothe status of a particular positioning technology module. For example,a phone status bar could be updated to show that GPS is active whenlocation information is being received.An application calls RPositionServer::NotifyModuleStatusEvent() to receive notification of module status changes, passing a reference to a TPositionModuleStatusEvent object on whichit has set the requested events.

An application also supplies a TRequestStatus object and optionally a TPositionModuleId object if statuschanges from only one module are required.When the status of a module changes, the client application is notified. The TPositionModuleStatusEvent object that was suppliedto the location server now also contains details of the events that haveoccurred and these are obtained by calling TPositionModuleStatusEvent::OccurredEvents().The following sections describe the steps to get module status changenotifications, as shown in the code example below.1.Define the types of module status events for which notification isrequired.The client application creates a TPositionModuleStatusEvent object with a TPositionModuleStatusEventBase::TModuleEvent variable which defines the status events in which it isinterested.2.Request module status change notifications.The client application calls the method RPositionServer::NotifyModuleStatusEvent() to make a request for modulestatus change notifications.Depending on whether the TPositionModuleId parameter ispassed to the function, the application is notified of status changesfor that given module only or for all modules.On completion, the TPositionModuleStatusEvent object holdsdetails of the types of events that have occurred.3.Check the types of status changes that have occurred.The TModuleStatusEvent object contains both the requestedevent types and the event types that occurred.• The requested event types are accessed by calling TPositionModuleStatusEvent::RequestedEvents().LOCATION-BASED SERVICES307• The event types that have occurred are accessed by callingTModuleStatusEvent::OccurredEvents().• Both of these methods return bit mask values of type TPositionModuleStatusEventBase::TModuleEvent.Partial updates can occur.

For example, an application can requestnotification of both device status and quality status changes and it willreceive notification when either one of these occurs. It may be necessaryfor an application to check the types of events that have occurred.A client application can only have one outstanding request for modulestatus updates per server session.

An attempt to make a second requestfor location information while one is still outstanding causes a panic. Anapplication must cancel an outstanding request before it makes anotherrequest.The sample code below demonstrates the discussed technique inits simplest form. Production-quality applications do not use User::Wait() but use an active object class to receive events, as the samplecode to accompany this recipe will illustrate.#include <lbs.h>// Assume that the app has established the session with// the location server (‘server’ variable)TPositionModuleStatus modStatus;TPositionModuleStatusEvent modEvents;// 1.

Define the types of status events for which notification is//requiredTPositionModuleStatusEventBase::TModuleEvent requestedEvents =TPositionModuleStatusEventBase::EEventDeviceStatus |TPositionModuleStatusEventBase::EEventDataQualityStatus;modEvents.SetRequestedEvents(requestedEvents);// 2. Request module status change notifications for all modulesTRequestStatus status;server.NotifyModuleStatusEvent(modEvents, status);// Wait for an event to occur.// Normally, the application should use an active object in// production code – this is for simplicity onlyUser::WaitForRequest(status);// 3. Check the types of status changes that have occurredTPositionModuleStatusEventBase::TModuleEvent occurredEvents =modEvents.OccurredEvents();// Check the type of event that occurred...modEvents.GetModuleStatus(modStatus);TPositionModuleStatus::TDeviceStatus deviceStatus =308SYMBIAN C++ RECIPESmodStatus.DeviceStatus();TPositionModuleStatus::TDataQualityStatus qualityStatus =modStatus.DataQualityStatus();if (deviceStatus == TPositionModuleStatus::EDeviceError){// Device error for this module}// Can check the data quality for the moduleif (qualityStatus == TPositionModuleStatus::EDataQualityLoss){// Loss of quality for this module}// Don’t forget to close the location server session!4.10.1.4Set the Module Selection CriteriaAmount 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 set positioning technology module selectioncriteria.Solution: Applications use the TPositionCriteria class to definemodule selection criteria.

Module selection criteria consist of:• The capabilities required of a module, for example, the ability toprovide speed or altitude data. The TPositionModuleInfo classdefines all those capabilities.• The quality of position required from a module, for example, arequired horizontal accuracy to within 100 meters and a time to obtaina position of not greater than 30 seconds. The TPositionQualityclass defines the quality of the position.• A relative ranking or ordering of the different quality of position parameters, for example, cost may be more important than accuracy. ClassTPositionSelectionOrder defines the relative importance of thedifferent quality values specified in TPositionQuality.

The location framework uses ordering to choose between candidate modulesthat could satisfy a client application’s module selection criteria.An application uses the method RPositioner::Open() to opena subsession with the location server. There are several overloadedOpen() methods that an application can use to open the subsession,one of which allows a TPositionCriteria object to be passed to theLOCATION-BASED SERVICES309location server. If the application passes a TPositionCriteria objectin RPositioner::Open(), the LBS framework:• chooses the positioning module with the capabilities that best matchthose specified in TPositionCriteriaBase::RequiredCapabilities().

The chosen module is used to obtain location updates for location requests made on the open client–serversubsession.• uses the position accuracy and timeout values specified in TPositionCriteriaBase::TPositionQuality() when the clientmakes RPositioner::NotifyPositionUpdate() locationrequests.A client application does not have to supply module selection criteriawhen it calls RPositioner::Open().

If no criteria are specified thena set of default criteria are used in which horizontal position (latitudeand longitude) is the only required module capability. The handsetmanufacturer or Symbian OS licensee may provide its own quality profileto be taken by default.If no criteria are given, the LBS APIs use default criteria that specifya horizontal accuracy of 50 meters, a vertical accuracy of 1,000 metersand a timeout of 30 seconds. The priority ranks accuracy first followedby least cost.The following sample demonstrates how to deal with various criteriaclasses in order to define certain requirements for positioning module. Itis quite simple and can be used in conjunction with the recipe, whichdescribes how to get position information:#include <lbs.h>RPositionServer server;RPositioner positioner;// Create a session with the location serverUser::LeaveIfError(server.Connect());CleanupClosePushL(server);// Define module selection criteriaTPositionCriteria criteria;TPositionQuality quality;TPositionSelectionOrder order;// Set required capabilities - want altitude information...criteria.AddRequiredCapabilities(TPositionModuleInfo::ECapabilityVertical);// Set quality - want vertical position within 100mquality.SetVerticalAccuracy(100);// Set ordering - make vertical accuracy a high priority310SYMBIAN C++ RECIPESUser::LeaveIfError(order.SetOrderVerticalAccuracy(TPositionSelectionOrder::EOrderHigh));criteria.SetRequiredQuality(quality);criteria.SetSelectionOrder(order);// Pass it to the Open() methodUser::LeaveIfError(positioner.Open(server, criteria));CleanupClosePushL(positioner);...// Close the subsession and sessionCleanupStack::PopAndDestroy(2, &server); // positioner, server4.10.2 Intermediate Recipes4.10.2.1Request Location InformationAmount of time required: 40 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 obtain location information.Solution: Client applications use the RPositionServer and RPositioner classes to get position updates.

RPositionServer is used byclient applications to manage a session with the location server and toget positioning technology module information. RPositioner is usedby client applications to manage a subsession with the location serverand to get position updates.For each location request from a client, the LBS subsystem can operatein one of several different positioning modes. The Location AcquisitionAPI hides most of the details of which positioning mode is in use fromclient applications. A client makes the same sequence of calls to the APIto get a position update whichever positioning mode is used.

Each modeis a different way of getting a position fix:•AutonomousLBS uses a GPS positioning module to calculate position fixes withoutassistance data from the network. This mode typically takes the longesttime to obtain a location fix compared with the other modes.• Terminal-Based PositioningLBS uses an A-GPS positioning module to calculate position fixes usingassistance data from the network. Assistance data specifies the GPSsatellites that are above the horizon as seen from the mobile device’sLOCATION-BASED SERVICES311current location. Assistance data is used by an A-GPS positioningmodule to reduce the time necessary to obtain a position fix.The network can also supply a reference position to the LBS subsystemas part of the sequence of events.

This position is calculated in thenetwork using cell-based techniques and may be less accurate thanthat obtained from GPS. A reference position may be returned to theclient before a GPS position. See Location Acquisition API runtimebehavior for more information about the position updates that can bereturned by LBS.• Terminal-Assisted PositioningLBS uses an A-GPS positioning module to obtain GPS measurements(using assistance data from the network). GPS measurements arethe raw data used to calculate a GPS fix. Measurements are sent tothe network and a position fix is calculated by a remote server. Theremotely calculated position fix is returned to the mobile device andis known as the final network position. The LBS subsystem returns thisposition to the client.• Hybrid PositioningThis mode is a combination of Terminal-Based Positioning andTerminal-Assisted Positioning.LBS passes GPS measurements to the network (as in Terminal-AssistedMode), but also attempts to use those measurements to calculate aGPS position fix (as in Terminal-Based Mode).

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

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

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

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