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

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

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

See the next recipe for an alternative option. The worst casescenario is to need to use the Cell ID information to identify thenetwork operator.4.8.1.8Retrieve the Current Operator NameAmount of time required: 10 minutesLocation of example code: Telephony_Monitor1Required library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): NoneProblem: You want to get the current operator name.Solution: The CTelephonyAppUi class shows how to retrieve the operator name.Discussion: You need to call CTelephony::GetOperatorName().When the current operator name has been retrieved, RunL() will becalled and the error code can be retrieved from the iStatus variable.The operator name is stored in a TOperatorNameV1 variable (ifiStatus is KErrNone), which only has one buffer variable iOperatorName, where the name for the currently used operator is stored.274SYMBIAN C++ RECIPESWhat may go wrong when you do this: Some network operators donot publish their name with this method, and thus you might get anempty string when using this class.

See the previous recipe for analternative option. The worst case scenario is to need to use the CellID information to identify the network operator.4.8.1.9Retrieve the Flight Mode StatusAmount of time required: 10 minutesLocation of example code: \Telephony\Telephony_Monitor1Required library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): NoneProblem: You want to find out whether the phone is in flight mode(off-line).Solution: The CTelephonyAppUi class shows how to use the FlightmodeStatus code.Discussion: You need to call the CTelephony::GetFlightMode()function. When the initial flight mode status has been retrieved, RunL()will be called.In order to monitor any flight mode status change, use the NotifyChange() function with the second parameter set to EFlightModeChange.Since we are using the same active object for two different requests,we keep track of what is currently being done using the iMonitoringvariable. The importance of this becomes clear when implementing theDoCancel() function to determine which request needs to be cancelled.The flight mode status value is stored in a TFlightModeV1 variable(if iStatus is KErrNone), which has one member variable callediFlightModeStatus.

The only two possible values for iFlightModeStatus are:• EFlightModeOff (flight mode is off, e.g., the phone can communicate).• EFlightModeOn (flight mode is on, e.g., the phone commication isdisabled).Note: If you want to set the flight mode on/off, you need to use aprofiles engine. To set the flight mode on, just set the Offline profileon, and to set it off, just set any other profile on.TELEPHONY4.8.1.10275Retrieve the Network Registration StatusAmount of time required: 15 minutesLocation of example code: \Telephony\Telephony_Monitor1Required library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): NoneProblem: You want to know what the network registration status is.Solution: The CTelephonyAppUi class shows how to use the RegistrationStatus code.Discussion: You need to call CTelephony::GetNetworkRegistrationStatus().

When the initial network registration status has beenretrieved, RunL() will be called.In order to monitor any network registration status change, use theNotifyChange() function with the second parameter set to ENetworkRegistrationStatusChange.Since we are using the same active object for two different requests,we keep track of what is currently being done using the iMonitoringvariable.

The importance of this becomes clear when implementing theDoCancel() function to determine which request needs to be cancelled.The network registration status values are stored in a TNetworkRegistrationV1 variable, which has one member variable callediRegStatus. The values for the network registration status are asfollows:• ERegistrationUnknown (registration status is not known).• ENotRegisteredNoService (no network detected, and currentlynot searching).• ENotRegisteredEmergencyOnly (network allowing only emergency calls detected).• ENotRegisteredSearching (not registered, but currently searching for networks).• ERegisteredBusy (registered, but network is busy).• ERegisteredOnHomeNetwork (registered on home network).• ERegistrationDenied (registration attempt was denied by thenetwork).• ERegisteredRoaming (registered in network that is not homenetwork).276SYMBIAN C++ RECIPES4.8.2 Intermediate Recipes4.8.2.1Retrieve the Phone Number from an Incoming/Outgoing CallAmount of time required: 15 minutesLocation of example code: \Telephony\Telephony_DialerRequired library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): ReadUserDataProblem: You want to get the phone number of an incoming/outgoingcall.Solution: To retrieve a remote phone number from an incoming call, thecall needs to be at least in the ringing state.To retrieve a remote phone number from an outgoing call, the callneeds to be at least in the dialing state.You will find the source code for this recipe in the same class as thecode for Recipe 4.8.1.3 (that’s CMyCallObserver), because this allowsus to retrieve the remote phone number at the first available opportunity,which is when the call state changes.The actual function call is GetCallInfo(), for which:1.The first parameter lets you choose between voice/data/fax lines.2.The second parameter is a TCallInfoV1 buffer, which will holdinformation for the call and includes the phone number for outgoingcalls.3.The third parameter is a TRemotePartyInfoV1 buffer, which holdsinformation on the remote party and may include the phone numberfor incoming calls (if it is available from the Call Line Identification).What may go wrong when you do this: Some devices have shown‘Out of Memory’ errors when using GetCallInfo() directly in astate change event callback, which is why the sample code containsan added User::After() delay before calling the method.

This ispresumably an internal defect.A better workaround would be to use a separate active objectto handle the delay, but it would need to be cancelled if the callterminated before the timer goes off.4.8.2.2Match a Name to a Phone NumberAmount of time required: 15 minutesLocation of example code: Telephony_DialerTELEPHONY277Required library(s): cntmodel.libRequired header file(s): cntdb.h, cntfield.h, cntfldst.h,cntitem.hRequired platform security capability(s): ReadUserData, WriteUserDataProblem: You want to identify the contact associated with a phonenumber.Solution: The CTelephonyAppUi class shows how to use the GetContactsName code.Discussion: Before using this recipe, you may want to look at the recipesin Section 4.2, which illustrate how to use the Symbian OS contactdatabase.To retrieve a name from a contacts database, you first need to construct an instance of the CContactDatabase class as shown in theConstructL() function.

Then, because we cannot assume that allnumbers are in international or national format (for example, +35840 . . .or just as 040), we need to extract the part of the number which wewant to use for processing. In this example, the last eight digits ofthe number are used (you can change this by changing the value forKTxMaxNumberCut).The sample sets up an asynchronous search of the entire contactdatabase by using KUidContactFieldMatchAll in a CContactItemFieldDef and calling FindAsyncL().When the first matching contact is found, IdleFindCallback()is called. Since there might just be one contact matching the searchcriterion, checking the result of IsComplete() lets us know whetherwe need to cancel the remainder of the search.Tip: This example only reports the first hit. If you want to get all ofthe matching results, you can easily retrieve all the CContactItemfrom their id and report each one back to the caller through theMContactsNameCallBack interface.4.8.2.3Retrieve the IMSI Number of the SIM CardAmount of time required: 15 minutesLocation of example code: \Telephony\Telephony_Monitor2Required library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): ReadDeviceDataProblem: You want to get the current SIM card identification number(IMSI).278SYMBIAN C++ RECIPESSolution: The CTelephonyAppUi class shows how to use the Imsi_Getter code.Discussion: You need to call the CTelephony::GetSubscriberId()function.

When the IMSI number of the SIM card has been retrieved,RunL() will be called and the error code can be retrieved from theiStatus variable.The IMSI number is stored in a TSubscriberIdV1 variable (ifiStatus is KErrNone), which only has one buffer variable iSubscriberId, where the IMSI number of the SIM card is stored. Thefirst three characters of the IMSI number identify the subscriber’s homecountry, the next two or three characters identify the operator used whilein the home country. The remaining characters are used to identify theindividual subscriber.Tip: Since each IMSI number is globally unique to a SIM card, you canuse this mechanism to generate application registration keys, insteadof using the IMEI number.4.8.2.4Retrieve the Phone Lock StatusAmount of time required: 20 minutesLocation of example code: \Telephony\Telephony_Monitor2Required library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): ReadDeviceDataProblem: You want to know the phone’s current lock status.Solution: The CTelephonyAppUi class shows how to use the LockInfo_Getter code.Discussion: You need to call CTelephony::GetLockInfo().

Thesecond parameter for this function allows you to choose which lock youare interested in. When the lock status has been retrieved, RunL() willbe called and the error code can be retrieved from the iStatus variable.The requested lock status is stored in a TIccLockInfoV1 variable (ifiStatus is KErrNone), which contains two fields:• iStatus (identifies whether the phone is locked, unlocked orblocked).• iSetting (identifies whether the specific lock is enabled or not).TELEPHONY279It is important to understand the difference between the locking statusand the locking setting values. A lock has a status which tells you itscurrent state, for example, whether it is locked, unlocked or blocked.

Alock also has a setting, which is more like a policy, which says if the lockshould be treated as ‘in use’. If the lock is enabled, then the status shouldbe observed. If the lock is disabled, then the status is not important.Note: Locking and unlocking the device requires usage of non-publicAPIs, thus if you need more information on the functionality, you wouldneed to contact the manufacturer of the device you are targeting.This functionality can also be achieved by using AT commands, ifthe target device supports AT commands for using the phone lock.4.8.3 Advanced Recipes4.8.3.1Retrieve Cell ID and Network InformationAmount of time required: 25 minutesLocation of example code: \Telephony\Telephony_Monitor2Required library(s): etel3rdparty.libRequired header file(s): etel3rdparty.hRequired platform security capability(s): ReadDeviceDataProblem: You want to get information about the currently used networkcell.Solution: The CTelephonyAppUi class shows how to use the NWInfo_Observer code.Discussion: You need to call CTelephony::GetCurrentNetworkInfo().

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

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

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

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