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

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

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

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

Several message-type specificclasses are provided for the purpose of extracting data from these stores.Examples of these message-type specific classes are:• CSmsHeaderfor SMS messages• CImEmailMessage for email messages.226RECEIVING MESSAGESA detailed exploration of these classes is beyond the scope of thisbook. However, documentation can be found in the Symbian OS Library.Attachment entriesAn email or MMS message entry may have associated attachment entries.Each attachment entry represents an attached file or media element.The attachment API should be used for accessing these attachments.

Anattachment manager object for a particular message can be accessed bycalling CMsvStore:: AttachmentManagerL(). Further informationon this API and the MMsvAttachmentManager interface can be foundin the Symbian OS Library. The CMsvStore object can be extracted froma CMsvEntry by calling CMsvEntry::ReadStoreL(). CMsvStoreis discussed later in this chapter.8.3.3 Message Entry APIsCMsvEntryIf there is one key class in the messaging APIs, then CMsvEntry is it.However, care should be taken when using CMsvEntry as inappropriateuse can seriously impact system performance and degrade the userexperience-specific advice on usage can be found in section 8.5.3.CMsvEntry is used for the following purposes:• to navigate around the message store• to enumerate the child entries, for example to retrieve a list of messageentries in the inbox.

Entries can be sorted by specified criteria• to retrieve the store for the message-type specific information (e.g.,email MIME headers)• for modification of entries (e.g., change, copy, move and deleteoperations).CMsvEntry can be thought of as a pointer to an entry in the messagestore. It may point to any type of entry, for example, a folder entry ora message entry.

It is common for a messaging application to use asingle CMsvEntry to point to a particular entry, to extract the requiredinformation, and then to set it to point at another entry.class CMessageSummaryEngine : public CActive, public MMsvSessionObserver{...// Symbian OS messaging classesCMsvSession* iMessagingSession;CMsvEntry* iMessagingEntry;...};THE MESSAGE STORE227void CMessageSummaryEngine::CreateSummaryGeneratorsL(){// Select the ordering we wish to use when enumerating through messages.// The message summary application is only interested in the most recent// messages so EMsvSortByDateReverse is appropriate.TMsvSelectionOrdering ordering(KMsvNoGrouping, EMsvSortByDateReverse);// Create the CMsvEntry object that will be shared by all summary// generators// Note that it is only possible to create the CMsvEntry once the// message session is connected.iMessagingEntry = CMsvEntry::NewL(*iMessagingSession,KMsvGlobalInBoxIndexEntryId, ordering);iSmsInboxSummary = new (ELeave)CMessageSummaryGenerator(KMsvGlobalInBoxIndexEntryId, KUidMsgTypeSMS,*iMessagingEntry);// Find the first POP3 mailboxTMsvId pop3MailboxId;if (FindPop3ServiceEntryL(pop3MailboxId)){iEmailInboxSummary = new (ELeave)CMessageSummaryGenerator(pop3MailboxId, KUidMsgTypePOP3,*iMessagingEntry);}}Example 8.4Creating a CMsvEntryExample 8.4 shows how a CMsvEntry object is created.

In thisexample three parameters are provided:• aMsvSession – a reference to the previously created messagingsession. Note that the session must be created before a CMsvEntrycan be instantiated. The CMsvEntry object will use this session tocommunicate with the message server.• aMsvId – the ID of the entry in the message store that this CMsvEntrywill initially be pointing at, in this case it is the local inbox.• aOrdering – the ordering preference for child entries. A CMsvEntryobject is often used for enumerating child entries, e.g., for listing allof the messages in a particular folder.

The ordering parameter is usedto determine the order in which child entries will appear in this list.The summary screen application is only interested in the most recentmessages, hence the EMsvSortByDateReverse ordering is used.In the example code the CMsvEntry object is created and then passedto the summary generator objects. For performance and RAM usage reasons it is desirable not to repeatedly create and delete CMsvEntryobjects.

Therefore, a reference to the original CMsvEntry is used in thiscase.228RECEIVING MESSAGESclass CMessageSummaryGenerator : public CBase{public:CMessageSummaryGenerator(TMsvId aInboxEntry,TUid aMessageType,CMsvEntry& aMessagingEntry);...private:CMsvEntry& iMessagingEntry;TMsvId iInboxEntry;TUid iMessageType;};Example 8.5The CMessageSummaryGenerator classTwo instances of the class in example 8.5 are created, one for SMS andone for email – each uses a reference to the same CMsvEntry class. Thesame code is used to generate the summaries for both message types. TheaMessageType and aInboxEntry parameters are used to determinewhich messages are searched for. For SMS messages the message type isset to SMS and the inbox is set to the local inbox; for email the messagetype is set to POP3 and the inbox is set to the POP3 service entry.

SeeFigure 8.4 for more details on where the different received message typesare stored.The aInbox parameter is used to target the search for new messages atthe appropriate folder. Targeting the search at specific folders as opposedto recursively searching the entire message store has two advantages:1.Any messages in the outbox, draft or any other local folders areignored.2.Needlessly searching through a large number of folders and entriescan be very time-consuming. Targeting the search at the appropriatefolder is much more efficient.Example 8.6 shows how messages of a particular type can beenumerated:void CMessageSummaryGenerator::StartL(TRequestStatus& aStatus){aStatus = KRequestPending;iMessageSummaries.Reset();// Set the CMsvEntry to point to the appropriate inbox, this will be the// global inbox for SMS or the remote POP3 inbox for email.iMessagingEntry.SetEntryL(iInboxEntry);// Get a list of the messages in the selected inbox of the type we are// looking for (e.g.

SMS or email)THE MESSAGE STORE229CMsvEntrySelection* filteredMessageIds =iMessagingEntry.ChildrenWithMtmL(iMessageType);CleanupStack::PushL(filteredMessageIds);... // function continues in Example 8.7 RExample 8.6Enumerating all messages of a particular type in an inboxSetEntry() is used to set the CMsvEntry to point at the appropriateinbox. For SMS this will be the local inbox, for email it will be the POP3inbox.Once the correct inbox is selected, ChildrenWithMtmL() is used toget the list of child entries of the appropriate message type (SMS or email).It is possible to get the list of all child entries by calling ChildrenL(). Ifthe local inbox was selected then ChildrenL() would return all of theSMS, MMS and OBEX messages that had been received.TMsvEntryThe TMsvEntry class encapsulates the generic information regardingan entry, for example the date, the subject, etc.

It is possible to get theTMsvEntry data for a particular entry by using one of several differentfunctions:• CMsvSession::GetEntry() – get the TMsvEntry data for anyentry from the session.• CMsvEntry::Entry() – get the TMsvEntry data for the currentlyselected message.• CMsvEntry::ChildDataL() – get the TMsvEntry data for anychild of the currently selected message.The summary screen application uses ChildDataL(), as can be seenin Example 8.7.void CMessageSummaryGenerator::StartL(TRequestStatus& aStatus){...

// continuing from Example 8.6// Calculate the number of messages to summariseTInt numberForSummary = filteredMessageIds->Count();if (numberForSummary > KMaxSummaryMessages)numberForSummary = KMaxSummaryMessages;TInt index;TMsvEntry tempDataEntry;for (index = 0; index < numberForSummary; index++)// Generate the message summaries{// Get the TMsvEntry data for the message at the current index.230RECEIVING MESSAGEStempDataEntry =iMessagingEntry.ChildDataL((*filteredMessageIds)[index]);// Copy the message details from TMsvEntry to the message summary// structure (TMessageSummary)TMessageSummary summary;summary.iFrom = tempDataEntry.iDetails.Left(KMaxSummaryStringSize);summary.iSummaryText =tempDataEntry.iDescription.Left(KMaxSummaryStringSize);iMessageSummaries.AppendL(summary);}TRequestStatus* status = &aStatus;User::RequestComplete(status, KErrNone);CleanupStack::Pop(filteredMessageIds);}Example 8.7Retrieving summaries for messagesChildDataL() is used as opposed to EntryL() because the latterwould have required the CMsvEntry to be set to each message entryin turn.

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

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

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

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