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

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

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

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

As mentioned previously, needlessly changing the context ofCMsvEntry can have serious performance implications for the application. This problem is avoided by using ChildDataL() which canextract the TMsvEntry data for the child message entries without theneed to repeatedly call CMsvEntry::SetEntry().In Example 8.7, the summaries for several messages are generatedsynchronously in one function. This is not a problem in this example,as KMaxSummaryMessages is set to three, so only three messages arechecked and the CMsvEntry is not moved.

However, if the CMsvEntry::SetEntry() was being called multiple times, or if the entireinbox was being enumerated, then it would desirable to derive fromCActive and break the operation up into several steps, repeatedly setting the object active and then completing it immediately. One stepshould then be performed in the RunL() each time the object completes.Message-type specific dataIn addition to the generic information encapsulated by the TMsvEntryeach message entry also has some message-type specific data, for exampleemail messages contain MIME header information.

This message-typespecific data is stored and retrieved using a CMsvStore object. TheCMsvStore object for a particular message entry is retrieved by callingCMsvEntry::ReadStoreL(). CMsvStore provides similar APIs tothe Symbian OS generic store and stream architecture.A client MTM will usually provide a utility class that can be used toextract the message-type specific data from the CMsvStore, for exampleCImHeader can be used to extract the MIME headers from an emailmessage.THE MESSAGE STORE231Some client MTMs also provide additional APIs that can be used tomanage attachments without accessing the store directly, for example,the email subsystem provides CImEmailMessage that can be used toretrieve the attachment data from a received email message.Note that retrieving message-type specific data is a much sloweroperation than retrieving the TMsvEntry data.

It is advisable to considerthe following guidelines in order to achieve good performance andresponsiveness:• Try to group all operations on a particular message in one place. Donot extract one header from each message in turn, and then do thesame for a different header. Instead, extract all required headers fromone message then move to the next one.• Implement iterative code as an active object where each message orattachment is processed in a separate call to the RunL function.

Thisis necessary to ensure that the application remains responsive evenwhen enumerating a large number of messages or attachments.MMsvSessionObserverPrevious code examples have shown how the MMsvSessionObserver::HandleSessionEventL() interface can be used todetermine when the messaging session has completed its initialization.After the session has been created, then this function is also called tonotify the observer of any subsequent changes to the messaging store.Examples include entry creation or deletion, and changes to existingentries.Example 8.8 shows how HandleSessionEventL() can be used torefresh the summary screen application when a new message has beenreceived: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::EMsvEntriesChanged:// Get the list of the changed messages. Note// that there may be more than one.CMsvEntrySelection* newMessages = static_cast<CMsvEntrySelection*>(aArg1);// Get the ID of the parent entryTMsvId* parentMsvId = static_cast<TMsvId*> (aArg2);// Set the CMsvEntry to point to the parent entryiMessagingEntry->SetEntryL(*parentMsvId);232RECEIVING MESSAGES// Add each new message to the appropriate message summaryTInt index = newMessages->Count() - 1;while (index >= 0){// Get the entry details for each new messageTMsvEntry tempMessageEntry =iMessagingEntry->ChildDataL(newMessages>At(index));if (tempMessageEntry.Complete())// Is the message// complete? Do not add incomplete entries.{if (iSmsInboxSummary->MessageOfCorrectType(tempMessageEntry)){iRefreshSms = ETrue;}else if ((iEmailInboxSummary != NULL) && (iEmailInboxSummary>MessageOfCorrectType(tempMessageEntry))){// If we have a new email message in the email inbox then// update the email summariesiRefreshEmail = ETrue;}}index--;}if ((iRefreshSms) | | (iRefreshEmail))// Refresh the SMS and / or email list if there have been any// changes to SMS and / or email messages{iState = ERefreshing;//////ifIf this object is not active then update the next summaryIf this object is active then the appropriate summary listwill be refreshed when it reaches the RunL.(!IsActive())UpdateNextSummary();}break;Example 8.8Monitoring the message store for updatesIt is possible that a message server plug-in (MTM) may create an incomplete entry in the inbox while the incoming message is being processed.

It isnot desirable for the summary screen application to display this incompletemessage. In order to get around this problem the above code checks forthe MMsvSessionObserver::EMsvEntriesChanged notification asopposed to MMsvSessionObserver::EMsvEntriesCreated. CMsvEntry::Complete() is then called to check that the changed messageentry has been flagged as complete. The summary screen is only refreshedif this flag is set.Note that this code will not currently update the inbox if a message isdeleted. In order to add this functionality, an additional case statement isrequired to handle the EMsvEntriesDeleted notification.MESSAGING APPLICATION DESIGN AND IMPLEMENTATION2338.4 Messaging Application Design and ImplementationWhen designing a messaging-aware application it is essential to considerhow it will access the message store.

If messaging APIs are used inappropriately then it is possible to seriously degrade the performance of theapplication and potentially the performance of the device. Some things toconsider when designing a messaging-aware application are listed below.8.4.1 Asynchronous BehaviourIt is usually advisable to make messaging operations as asynchronousas possible. This is desirable because many messaging operations canpotentially be long running, for example, enumerating all messages in theinbox, which may number in the hundreds. If potentially large numbersof messages are to be processed then an active object should be used,processing only a small number of messages – about 10 would be arecommended value – in each RunL() call. This will help to ensurethat the application remains responsive to user input and that it can becancelled at any time.The summary screen application uses an active object to refresh theSMS and email summaries in two steps.

This also allows the singleCMsvEntry to be shared between both objects, as they perform theiroperations sequentially.class CMessageSummaryEngine : public CActive, public MMsvSessionObserver{public:...// Start the summary operationvoid StartL();// CActive functionsvoid DoCancel();void RunL();...};Example 8.9Class declaration for CMessageSummaryEngineThe RunL() is called once for each message type. This means thatthe operation can be cancelled without waiting for all of the summariesto be updated. It also allows other active objects to run, for example anyactive objects that may be responsible for updating the UI. This would beeven more important if more message types were enumerated in additionto email and SMS, or when there are a significant number of emails orSMSs in a folder.234RECEIVING MESSAGESvoid CMessageSummaryEngine::RunL(){// One of the message summary generators has completed.if (!UpdateNextSummary()){// If UpdateNextSummary returns EFalse then there are no more message// types to check.

So refresh the UI.iObserver.Refresh();}}Example 8.10 Updating the summary screen in stages to prevent theUI becoming unresponsiveIn addition to using active objects to break up large iterative tasksinto smaller steps, it is usually desirable to use the asynchronous versionof messaging APIs in cases where both synchronous and asynchronousversions are available.8.4.2 Applying Changes to the Message StoreTwo things happen every time a message store entry is changed:1.The observer of every messaging session in the system is notified ofthe change.2.There is a significant volume of file system access.When applying changes to the message store it is recommendedthat they are submitted as one operation.

For example, it is not desirable to repeatedly call CMsvEntry::ChangeL() to modify individualTMsvEntry flags. A better approach is to collate all of the changesrequired to the TMsvEntry and then to apply them all at once.8.4.3 Using CMsvSession and CMsvEntrySome key recommendations regarding the messaging classes are listedbelow.

It is worth considering these general rules when designing amessaging-related application.• Only create one CMsvSession object per application. If you needmore observers then use the CMsvSession::AddObserverL()function.• Do not add unnecessary observers. Note how a single observer isused in the summary screen application. This observer then delegatesto other classes depending on the contents of each notification.RECEIVING APPLICATION-SPECIFIC SMS MESSAGES235• Do not move a CMsvEntry object to point to different entriesunnecessarily.• Do not leave a CMsvEntry pointing at an entry that another application may want to delete. For example do not leave a CMsvEntrypointing at an entry in the inbox because this will prevent the userfrom deleting this message.• Do not leave a CMsvEntry pointing at a folder which contains lotsof child entries (e.g., the inbox) as this uses lots of RAM.8.5 Receiving Application-specific SMS MessagesThe messaging APIs usually provide the most convenient access tomessaging-related functionality.

However, there are some cases wherethese APIs are not appropriate. The most common example of this iswhen it is necessary to intercept a message before it is written to themessage store, as the addition of messages to the inbox typically triggersa user notification.The example summary screen application implements a weather reportfunction that is activated when a specially formatted SMS is received.One approach would be to use a messaging observer to wait for a newSMS message to appear in the inbox. When the new SMS is received,HandleSessionEventL() would be called.

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

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

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

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