Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 68

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 68 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 682018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In response to this, the Connect() is performed onthe socket to hook it to the rainmaker.wunderground.com server atport address 3000 and the state changes to EConnecting.Upon the Connect() completion, RunL() is called again, invokingthe RSocket Send() method to send the city code. The state is changedto ESending.Once the Send() completes, the RunL() calls RecvOneOrMore()to start getting the weather data. The state changes to EReceivingand remains in this state as long as the data keeps coming from theserver (although, in this case, you will probably get all the data onthe first call). RunL() looks for the end of the lines of ‘=’ characters352SYMBIAN OS TCP/IP NETWORK PROGRAMMINGRHostResolver::GetByName()EResolvingNameRSocket::Connect()EConnectingRSocket::Send()ESendingRSocket::RecvOneOrMore()EReceivingContinuecollecting dataCallback throughMWeatherObserver::TemperatureReport()orMWeatherObserver::TemperatureError()Figure 11.4 Weather Example State Machine(see Figure 11.3), which immediately precede the temperature.

Oncethe temperature is found, it calls the TemperatureReport() functionof the MWeatherObserver class passed in on the NewL() (stored iniObserver), passing it the city code and the temperature. If an erroroccurs at any time, the method CWeatherInfo::Cleanup() is called,which is implemented as follows:void CWeatherInfo::Cleanup(TInt aError){iSocket.Close();iSocketSrv.Close();iResolver.Close();TBuf<50> errStr;if (aError!=KErrNone){switch (iCommState){case EInitializing:{EXAMPLE: RETRIEVING WEATHER INFORMATION353_LIT(KErrStr,"Error initializing communications");errStr.Copy(KErrStr);break;}case EResolvingName:{_LIT(KErrStr,"Error resolving name");errStr.Copy(KErrStr);break;}case EConnecting:{_LIT(KErrStr,"Error connecting to server");errStr.Copy(KErrStr);break;}case ESending:{_LIT(KErrStr,"Error sending request");errStr.Copy(KErrStr);break;}case EReceiving:{_LIT(KErrStr,"Error receiving data");errStr.Copy(KErrStr);break;}default:{_LIT(KErrStr,"Unknown error");errStr.Copy(KErrStr);break;}}iObserver.TemperatureError(errStr,aError);}}Cleanup() closes all the network objects (it does not hurt to callClose() on a handle that is not yet open), and creates an error message based on what the state stored in iCommState is at the timeof the error.

It then invokes the observer’s TemperatureError()callback function, passing it the error message along with the errorcode.11.4.2Adding this Code to SimpleExThe full sample code for adding the functionality described above tothe S60 and UIQ versions of SimpleEx is available from the websitefor this book, which can be found on the Symbian Developer Networkwiki (http://developer.symbian.com/wiki). Here are the basic steps I354SYMBIAN OS TCP/IP NETWORK PROGRAMMINGperformed to integrate this functionality in SimpleEx:1.I added a new menu item called ‘Get temperature’ to the resourcefile, changing the menu definition for S60 and the commandresource for UIQ. I named the command ESimpleExTemperatureCommand.2.I added the ESimpleExTemperatureCommand to the commandenum in the program’s simpleEx.hrh file.3.For S60, I added the MWeatherObserver interface to CSimpleExAppUI in the class definition using multiple inheritance andadded to the class the two virtual functions of MWeatherObserverthat must be overridden:class CSimpleExAppUi : public CAknAppUi, public MWeatherObserver{...// from MWeatherObservervirtual void TemperatureReport(TDesC& aCity,TDesC& aTemperature);virtual void TemperatureError(TDesC& aErrorStr,TInt aErrCode);...};For UIQ, I added this interface to CSimpleExAppView instead ofCSimpleExAppUi (I wanted it where the application UI handlerresides).4.I added a private member variable, CWeatherInfo *iWeather,to the CSimpleExAppUI class in the case of S60, and to theCSimpleExAppView class in the case of UIQ.5.I included the previously listed example source (either in separatefiles or in the existing source and include files).6.In the CSimpleExAppUi::ConstructL() (CSimpleExAppView::ConstructL() for UIQ) I added the statement:iWeather = CWeatherInfo::NewL(*this);to create the example’s active object.7.In the CSimpleExAppUi destructor I added:delete iWeather;8.In the CSimpleExAppUi::HandleCommandL() (CSimpleExAppView::HandleCommandL() for UIQ), I added a case forthe command ESimpleExTemperatureCommand, which looksEXAMPLE: RETRIEVING WEATHER INFORMATION355as follows:case ESimpleExTemperatureCommand:{// Display the temperature in Austin, TX_LIT(KCityCode,"AUS");iWeather->GetTemperature(KCityCode);}9.I overrode the callback functions of the MWeatherObserver asfollows:void CSimpleExAppUi::TemperatureReport(TDesC& aCity,TDesC& aTemp){TBuf<50> str;_LIT(KTempTitle,"Report:");_LIT(KTempMessage,"Temperature in %S is %S");str.Format(KTempMessage,&aCity,&aTemp);TRAPD(res,iEikonEnv->InfoWinL(KTempTitle,str));}void CSimpleExAppUi::TemperatureError(TDesC& aErrStr,TInt aErrCode){TBuf<50> str;_LIT(KErrTitle,"Error:");_LIT(KErrMsg,"%S (%d)");str.Format(KErrMsg,&aErrStr,aErrCode);TRAPD(res, iEikonEnv->InfoWinL(KErrTitle, str));}Again, I did this in CSimpleExAppView class for the UIQ version.10.In the MMP file, I added insock.lib and esock.lib to theLIBRARY line, to include the libraries which implement the socketcalls.

I also added the line CAPABILITY NetworkServices,since, as I mentioned previously, the application requires thatcapability to communicate on the network. If you do not have thiscapability, the network API calls will fail.Build and run the updated SimpleEx program on the phone (Chapter 2shows how to use makesis to create a SIS file to enable you to installand run SimpleEx on the phone). When you select the ’Get temperature’ menu option, a network connection will be established. Once thecommunication is complete, the temperature of the city you requested (inthis case it is hardcoded to AUS, but you could modify to have the userenter it) is displayed on the screen.

Figure 11.5 shows the output of thisexample on an S60 device.Since the example uses an active object, you’ll note that the GUI is stillresponsive while the communication is taking place. For example, theStart menu item can be selected during the network communication356SYMBIAN OS TCP/IP NETWORK PROGRAMMINGFigure 11.5 Weather Example Screenand it will still display its dialog boxes. So, in effect, the entire networksequence to collect the weather information is running in the background.11.5Making a Network ConnectionUp to this point, we have not discussed how the network connectionsthemselves are represented and brought up, and we just relied on theoperating system to select the connection for us implicitly (while in manycases it will prompt the user for a connection) in our examples. Thissection will give a very brief overview of connections in Symbian OS.You should consult the SDK documentation for more details.On a Symbian OS smartphone, network connections are representedby Internet Access Points (IAPs).

IAPs can be created from the phone’scontrol panel, usually during initial setup. The information in an IAPincludes the physical connection type (such as GPRS or CSD), and thespecific attributes applicable to the selected connection type (such asthe phone number; user’s identifier and password for a dialup server,for CSD-type connections; or APN for a GPRS connection). You assign aname to the IAP when creating it, and that name is used when establishingthe connection.For example, you can create an IAP called T-Mobile GPRS to use theAPN provided by T-Mobile (e.g., Internet2.voicestream.com or general.t-mobile.co.uk).

Then, when you are prompted for a connection by thephone, you select T-Mobile GPRS to use the GPRS connection.Note that IAP setup varies from phone to phone, and also depends onthe particular service you intend to access. In many cases the IAP creationis done automatically for you (e.g., via your SIM or through a service SMSmessage).MAKING A NETWORK CONNECTION35711.5.1 Establishing a Connection for a ProgramThe example Symbian OS socket code, presented in section 11.3, createdand used a socket as if the smartphone connection was already established. In fact, this is often done in Symbian OS and is known as animplicit connection.

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

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

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

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