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

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

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

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

The message server provides the following functionality:• Storing and retrieving messages using the message store.• Allowing multiple client applications to receive, create and sendmessages.• Notifying multiple client applications of changes to the message store,e.g., when a new message is received.The message server can be extended to support new message types byimplementing additional MTMs. A simple MTM example, which extendsthe SendAs service with a new transport type, is covered in Chapter 9.The remainder of this chapter concentrates on how client applicationscan access messaging functionality using the built-in message types.

Theexamples used in this chapter include SMS and POP3 email. However,the key concepts presented here also apply to other message types, suchas MMS.8.2.2 Message Server SessionThe first messaging-related task that a client application must perform isto open a session to the message server. The messaging session allows aclient application to examine the message store, create and send messagesand to be notified of any messaging-related events (for example a receivedSMS message).Example 8.1 shows the declaration of the messaging session.class CMessageSummaryEngine : public CActive, public MMsvSessionObserver{public:...THE MESSAGE SERVER221void HandleSessionEventL(TMsvSessionEvent aEvent, TAny *aArg1, TAny*aArg2, TAny *aArg3);...private:...// Symbian OS messaging classesCMsvSession* iMessagingSession;};Example 8.1 Part of the class declaration for the messaging summaryengine, showing the message server interfacesThe message server session is encapsulated by the CMsvSessionclass.

It is highly recommended that only one CMsvSession objectis instantiated per application because additional sessions will have animpact on system performance and RAM usage.Classes that own a CMsvSession will usually implement the MMsvSessionObserver interface. The MMsvSessionObserver interface(specifically HandleSessionEventL()) is called by the message serverto notify the client about message server events, for example that a newmessage has been created (see Figure 8.3).Example 8.2 shows how the CMsvSession is created:// Start the summary operationvoid CMessageSummaryEngine::StartL(){// Connect to the Message Server asynchronouslyiState = EConnectingToMessageServer;iMessagingSession = CMsvSession::OpenAsyncL(*this);// The message server will call HandleSessionEventL when the session is// connected.}Example 8.2Creating the CMsvSessionIn the above example the CMsvSession is created by callingOpenAsyncL().

The ‘this’ parameter is passed in so that CMessageSummaryEngine is notified about future message server eventsCMsvSession callsMMsvSessionObserver interface withmessaging events.1MMsvSessionObserver1CMsvSession11CMessageSummaryEngineFigure 8.3 Interfacing with the messaging session classes222RECEIVING MESSAGESvia its HandleSessionEventL() function. This is possible becauseCMessageSummaryEngine is derived from MMsvSessionObserver.The client application does not require any platform security capabilities in order to open a CMsvSession.

However, subsequent calls tothe message client APIs may require specific capabilities depending onthe operation type, for example, putting an email message in the outboxrequires ReadUserData, WriteUserData and NetworkServices.It is possible to create a messaging session either synchronously orasynchronously. This example uses the asynchronous version. There areseveral advantages to using asynchronous function calls for potentiallylong-running operations such as the creation of the messaging session:1.The application remains responsive to user input.2.Other active objects in the application thread may continue to run,performing other tasks while the messaging session is being created.The message server signals that the messaging session has been createdby calling the HandleSessionEventL function. The CMsvSessionclass cannot be used until this function has been called.void CMessageSummaryEngine::HandleSessionEventL(TMsvSessionEvent aEvent,TAny *aArg1, TAny *aArg2, TAny* /* aArg3 */)// This function is called by the message server for// every message server event,// e.g.

when a new message is received or created.{switch (aEvent){case MMsvSessionObserver::EMsvServerReady:// The session is now connected to the message serverif (iState == EConnectingToMessageServer){// Create the summary generators for each message typeCreateSummaryGeneratorsL();// If we were waiting for connection to the message server thenmove // on to the next state, update the message summaries.UpdateNextSummary();}break;...}}Example 8.3Waiting for the message server connect to completeThe aEvent parameter is used to determine the type of the notification.The code in example 8.3 checks the aEvent parameter to determine if themessaging session is initialized and then initiates the message summarygeneration.THE MESSAGE STORE2238.3 The Message Store8.3.1 Message Store StructureThe message store uses a tree structure to store messages.

Every node inthe tree structure is represented by an entry. Each entry can be one offour different types:• Folder entry – used to group messages in much the same way as adirectory in the file system is used to group files. Examples of folderentries include the inbox and the outbox.• Message entry – used to store the contents of a particular message.One message entry is created for each message in the store. Note thatsome message types have child attachment entries which are used tostore attachment data.• Service entry – represents an external messaging account, for examplea POP3 mailbox or an MMS account.In versions of Symbian OS prior to v9.0 these service entries held themessage account settings, for example POP3 server address, user nameand password.

However, in v9.0 onwards this information is stored inthe Central Repository and is accessed via message-type specific APIsprovided by the client MTM.• Attachment entry – used to store the attachment or multimedia datafor some message types.Figure 8.4 shows an example message store structure, populated withassorted accounts and messages. It shows several SMS messages in theinbox and three different email accounts (two POP3 and one IMAP4).Note that Figure 8.4 is a simplified representation of a typical messagestore. Each email message would usually have several correspondingattachment entries and additional folders would be present under thelocal service entry, for example a Drafts folder and a Sent folder.Received push messages, for example SMS and MMS, are initiallystored in the local inbox.

A client application may later move the messageentry to another location, for example the ‘saved messages’ folder.Received POP3 and IMAP4 messages are stored under the appropriateservice entry. The structure under this service entry corresponds to themessage structure on the email server.8.3.2 Message EntriesJust as the message store is broken up into entries, each individual entryalso has a number of distinct components: some of these components224RECEIVING MESSAGESRoot EntryLocal(service entry)Inbox(folder entry)Email (POP3)(service entry)Email message(message entry)SMS message(messageentry)Email message(message entry)SMS message(messageentry)Email message(message entry)Email (POP3)(service entry)Email message(message entry)Email (IMAP)(service entry)Email message(message entry)Email message(message entry)SMS message(messageentry)Figure 8.4Simplified version of the contents of a typical message storeare generic to all message types and some are specific to a particularmessaging technology.

The structure of an individual message entry isshown in Figure 8.5.We’ll now look at the generic message attributes and message-typespecific streams.Generic message attributesThe exact format of each message entry depends on the message typeand the state of the message. However, there are some attributes that arecommon to all message entries, for example:• subject (or summary)• date• sender/recipient details.These common attributes are accessed using the same APIs, regardlessof the message type.

This design means that it is possible to use the samesource code to process the summary information for different messagetypes. This is illustrated in the example summary screen applicationwhich uses the same class, CMessageSummaryGenerator, to generateTHE MESSAGE STORE225Message EntryGeneric message attributesTMsvEntrye.g. subject, sender, recipient, date, etc..Store(CMsvStore)Body text stream(CMsvStream)Messsage type specific data stream(CMsvStream)e.g. Email MIME headersAttachment entry(optional)Figure 8.5Attachment entry(optional)Structure of an individual message entrythe summary information for email and SMS messages. There is no codein this class that is specific to either SMS or email.Some message types have a main text part – for an email (or MIME)message this would be the body text.

Message-type specific APIs canbe used to extract this body text, for example, CImEmailMessage::GetBodyTextL(). There are generic methods for extracting body text,but they do not handle character conversion for some message types, soit is better to use the message-type specific APIs if they are available.Message-type specific dataIn addition to the generic attributes, each message entry also has someinformation that is specific to the message type, for example emailmessages have MIME headers, and SMS messages have an associatedservice centre address. Each message entry has an associated storefor these message-type specific attributes.

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

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

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

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