Главная » Просмотр файлов » Symbian OS Communications

Symbian OS Communications (779884), страница 51

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

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

The chapter concludeswith an example of how to extend the messaging architecture by implementing a Flickr MTM, building upon the HTTP example code providedin Chapter 11 to upload an image to Flickr.The chapter is useful for developers wishing to implement a Sendmenu in their application and to those wishing to extend the Send menu.It provides a starting point to implementing a fully fledged set of MTMs.There are four main use cases which might have you looking at themessaging APIs:1.

Implementing services such as SMS-based services/games, or inboxcleaners.2. Using the SendAs API to transfer content between devices.3. Extending the options on the Send menu.4. Implementing a new message transport such as a push email MTM.We saw how to implement (1) in Chapter 8. The first part of this chaptercovers (2), and the second part covers (3) fully, as well as providing abasis for (4).Be aware that implementing new message transports requires yourcode to be trusted with capabilities from the extended capabilityset, including ReadDeviceData, WriteDeviceData, ProtServ242SENDING MESSAGESFigure 9.1The SendWorkBench application on S60and NetworkControl.

It is advisable to investigate the signingrequirements for such code before starting implementation.9.1 Examples Provided in this ChapterThere are two main parts to the example code for this chapter.The first is a SendWorkBench application (with S60 and UIQ versions),which demonstrates the use of SendAs to create SMSs and emails, andSendUI to offer the user a choice of how to send one message with textand one with attachments (see Figure 9.1).The second is an implementation of a set of MTMs, which add a ‘Sendto Flickr’ item to the Send menu of S60 and UIQ.9.2 SendAs Overview9.2.1 SendAs MessagingSendAs is an API which presents a simple abstraction over the variousmessaging technologies found in mobile devices.SendAs extends the messaging architecture and adds a new layer ontop, enabling the discovery and use of protocols for sending data fromthe device.

An application using SendAs describes the type and size ofdata it would like to send, and can discover message types that are ableto accommodate the payload.SENDAS OVERVIEW243SendAs can also launch a message editor to allow the user to modifythe message before sending, as in the case of following a ‘mailto:’ link ina web browser – the browser creates an empty email with the recipientfield filled in.Different methods of sending may have varying costs to the user. AnSMS is typically charged per message, while sending an email over WLANoften adds no extra cost – therefore an application usually offers the usera choice of compatible bearers.SendAs can be used directly to create this list, but UI platforms providewrappers around this functionality to allow easier integration into a UIapplication.9.2.2 The Send DialogUIQ and S60 provide UI-level APIs for adding a Send item to an application’s menu, layered on top of the SendAs API.

The term ‘SendUI’ isoften used to refer to the DLL which provides these services, but for thepurpose of this chapter the term Send menu refers to the menu or dialogprovided by the respective UI (see Figure 9.2).On S60 the Send dialog API is provided by the CSendUi classand sendui.lib; on UIQ it is provided by CQikSendAsDialog,CQikSendAsLogic and qikutils.lib.A Send dialog offers the user a choice of sending methods compatiblewith the data being sent.

The choice given to the user may further befiltered if no accounts exist for a particular MTM, for example, there isFigure 9.2Send menus on S60 3rd edition and UIQ3244SENDING MESSAGESno point allowing the user to ‘send via email’ if no email accounts havebeen defined.Both SendAs and the various Send dialog APIs take advantage of thefact that all bearers can handle data as either text or as an attachment toprovide a uniform API for querying capabilities and creating messages.9.2.3 When to use SendAsSendAs and the Send dialogs have similar roles in that both UIQ andS60 classes wrap up message creation in a similar way. The Senddialogs require an application environment (CEikonEnv), and are notsuited to a background service, whereas any thread or process can useRSendAs.• Use the Send dialog when your application has data to send, but youwant to let the user choose which transport to use.• Use RSendAs when you know the transport and contact address, forexample, when sending an SMS to a fixed number.9.2.4 SendAs OverviewRSendAs and RSendAsMessage are the main classes which make upthe Symbian ‘SendAs’ API.

They provide the following services:• list all MTMs installed or those that have specific capabilities• list services/accounts available for each MTM• create and send a message with confirmation from the user• create and send a message without confirmation from the user (if theapplication does not have the capabilities required to send a messageusing a given MTM then the user will be prompted as to whether toallow the message to be sent)• create and launch the appropriate editor, delegating the modificationand sending of the message to the editor• create and save messages to the drafts folder for opening from themessaging application.9.2.5 Messaging on a Real DeviceDifferent devices are likely to have different sets of MTMs installed – thechoice is down to the device manufacturer.

Equally, the emulator suppliedin the various SDKs may have a variable set of MTMs installed. ThereforeSENDAS OVERVIEW245Application/ServiceSend asMessage ServerIR OBEX MTMSMTP MTMMMS MTMSMS MTMBluetooth OBEX MTM...Figure 9.3 High-level diagram of a messaging subsystem on a typical phoneit’s not always possible to guarantee that a particular bearer is availableon a device. An obvious example would be the IR OBEX MTM. If a devicehas no IrDA transceiver then the IR OBEX MTM will not be built in tothe device. Unless you are targeting a specific device, then it’s best notto make assumptions about installed MTMs.Figure 9.3 shows a typical array of MTMs installed on a device.It’s worth noting that the MMS MTM has different implementationsand APIs on UIQ and S60.

Using SendAs will shield you from thesedifferences.9.2.6 Basic CapabilitiesEach MTM reports whether it supports body text and attachment attributes.(see the table below).BearerSupports body textBluetooth×Infrared×SMSMMSEmail√×√Supports attachment√√×√√246SENDING MESSAGES9.3 Services/AccountsEach MTM may have zero or more services associated with it. Thepurpose of a service is to store settings or account details for an MTM. Anemail account is defined by two services – one for incoming messages(POP3/IMAP) and one for outgoing messages (SMTP). If no account issupplied to SendAs, or Send dialog, then the default account is used.The concept of a default account is consistent throughout all SymbianOS-based devices, so unless there is a specific reason then SendAs clientsshould always stick to the default.9.4 Technical DescriptionFigure 9.4 shows how SendAs fits into the overall messaging architecture.There are two process boundaries in place in order to allow policing ofcapabilities at both the message server interface and for clients of SendAs.Application/Service usingsend asRSendAsMessageRSendAsClient server boundaryUI DATA MTMSendAs ServerUI MTMClient MTMCMsvSessionClient server boundaryMessage serverServer MTMMessage storeFigure 9.4Integration of the SendAs service with the messaging architectureTECHNICAL DESCRIPTION247The application/SendAs server process boundary means that whilst theSendAs server must have the platsec capabilities to write messages to themessage store, SendAs clients do not.If a SendAs client without the appropriate capabilities attempts to senda message, then SendAs will first prompt the user to confirm the send.A client which wishes to silently send messages from a backgroundservice must have all the capabilities that are required by both the messageserver and the MTM being used.S60 3rd edition and S60 3rd edition Feature Pack 1 use a slightlymodified version of this architecture without the interim SendAs server.This means that the client-side MTMs need to be signed with enoughcapabilities to be loaded into the client process, rather than being loadedinto the SendAs server process.

More details can be found in the S60 3rdedition SDK documentation, including a list of the capabilities requiredby the client-side MTMs.9.4.1 Sending a One-shot SMSTo give a flavour of the practical use of SendAs, the following examplecode fragment sends an SMS to a fixed, fictional, phone number.//Link against sendas2.lib#include <smut.h> // for KUidMsgTypeSMS#include <sendas.h>#include <rsendasmessage.h>void SendAnSMSL(){_LIT(KSMSRecipient, "+447700900007");_LIT(KSMSBodyText, "Some body text to fill up space");RSendAs sendAs;User::LeaveIfError(sendAs.Connect());CleanupClosePushL(sendAs);RSendAsMessage sendAsMessage;sendAsMessage.CreateL(sendAs, KUidMsgTypeSMS);CleanupClosePushL(sendAsMessage);// prepare the messagesendAsMessage.AddRecipientL(KSMSRecipiant),RSendAsMessage::ESendAsRecipientTo);sendAsMessage.SetBodyTextL(KSMSBodyText);// send the messagesendAsMessage.SendMessageAndCloseL();CleanupStack::PopAndDestroy(2,&sendAs);}Creating the message and adding the recipient is pretty straightforward:ESendAsRecipientTo is used to denote that the recipient should beadded to the To: list, which for SMS is the only list.248SENDING MESSAGESIf we were sending via email then ESendAsRecipientCc orESendAsRecipientBcc could be specified for carbon copy and blindcarbon copy recipients, respectively.RSendAsMessage::SendMessageAndCloseL() starts sendingthe message and closes the handle.

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

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

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

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