quick_recipes (779892), страница 32

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

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

The object’sinitial context is set to KMsvNullIndexEntryId, so as not to use upmemory or lock any message entries while the object is not in use. (Notethat the Cancel() function also finishes by setting the CMsvEntry andCSmsClientMtm objects to point to KMsvNullIndexEntryId, for thesame reason.)The functions in the SMS client MTM class, CSmsClientMtm, providea useful interface to SMS-specific messaging functionality. There areequivalent client MTM classes for email (such as CSmtpClientMtm)and MMS (CMmsClientMtm), although the latter is part of the UI, so maybe implementation-dependent.We construct the CMsvEntry and CSmsClientMtm classes in theConstructL() function, once we know the session is ready; thoseclasses take a reference to the opened session as a parameter.

The SMS180SYMBIAN C++ RECIPESMTM is accessed by casting from the base class pointer returned byCClientMtmRegistry::NewMtmL().#include <msvids.h> // TMsvIds for standard folders#include <smut.h> // KUidMsgTypeSMSvoid CSmsManager::ConstructL(){TMsvSelectionOrdering noOrdering;iEntry = CMsvEntry::NewL(*iSession,KMsvNullIndexEntryId, noOrdering);CClientMtmRegistry* mtmReg = CClientMtmRegistry::NewL(*iSession);CleanupStack::PushL(mtmReg);CBaseMtm* mtm = mtmReg->NewMtmL(KUidMsgTypeSMS);iSmsMtm = static_cast<CSmsClientMtm*>(mtm);CleanupStack::PopAndDestroy(mtmReg);}4.4.5.2Create a FolderAmount of time required: 10 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): msvapi.h, msvids.h, msvuids.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to create a custom folder for your application.Solution: We call the CMsvEntry::CreateL() function, specifyingthe KUidMsvFolderEntry type.Description: We use an active object class because we are using an asynchronous overload of CreateL().

Asynchronous CMsvEntry functionsreturn a CMsvOperation object, an interface which allows us to getinformation on how the function is progressing (particularly useful whenacting on more than one entry), and cancel the function.Note that we do not create a new CMsvEntry object, but store areference to the one owned by CSmsManager.#include <msvapi.h> // CMsvOperationclass CSmsCreator : public CActive{public: // methodsvoid CreateFolderEntryL(TRequestStatus& aStatus);private: // dataCMsvEntry& iEntry;CMsvOperation* iOperation;TMsvEntry iFolderHeader;};MESSAGING181We set our CMsvEntry to the parent of the new entry; in this case,to the local service entry as we want to create a local folder.

We set therelevant attributes in our TMsvEntry object (remember that iType andiMtm must be set for a non-service entry to be valid); the entry should bemarked as in preparation and not visible at this point to show that it is notyet ready to be displayed. Finally we start the folder creation by callingCreateL() and SetActive().#include <msvids.h> // TMsvIds for standard folders#include <msvuids.h> // KUidMsvFolderEntry, KUidMsvLocalServiceMtmvoid CSmsCreator::CreateFolderEntryL(TRequestStatus& aStatus){iEntry.SetEntryL(KMsvLocalServiceIndexEntryId);iFolderHeader.SetInPreparation(ETrue);iFolderHeader.SetVisible(EFalse);iFolderHeader.iType = KUidMsvFolderEntry;iFolderHeader.iServiceId = KMsvLocalServiceIndexEntryId;iFolderHeader.iMtm = KUidMsvLocalServiceMtm;iFolderHeader.SetReadOnly(EFalse);iOperation = iEntry.CreateL(iFolderHeader, iStatus);SetActive ();}Following good practice, we check the value of iStatus uponcompletion of CreateL(); if it is KErrNone, the message has beensuccessfully created.

We then set iEntry to point to the new folderentry so that the SMS Manager can store the folder’s TMsvId. If thisfailed, we would lose track of the new entry, and although it wouldbe retrievable by enumerating the children of the local service entry,we have chosen to use the functions CleanupEntryPushL() andCleanupEntryPop() from the CMsvSession class, which, as wellas performing normal cleanup, would also remove the folder from themessage store in the event that SetEntryL() was to leave. Once wehave done this, we update the InPreparation and Visible flags andcall CMsvEntry::ChangeL() to commit these changes to the messagestore.void CSmsCreator::RunL(){User::LeaveIfError(iStatus.Int());...iEntry.Session().CleanupEntryPushL(iFolderHeader.Id());iEntry.SetEntryL(iFolderHeader.Id());iEntry.Session().CleanupEntryPop(1);iFolderHeader.SetVisible(ETrue);iFolderHeader.SetInPreparation(EFalse);iEntry.ChangeL(iFolderHeader);...}1824.4.5.3SYMBIAN C++ RECIPESCreate a MessageAmount of time required: 10 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.lib, etext.libRequired header file(s): msvapi.h, smsclnt.h, txtrich.h,mtmdef.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to create a new outgoing message.Solution: We use the client MTM’s CreateMessageL() function, addrecipient addresses and attachments as required, and set any otherrelevant settings such as the message subject.Description: It is possible to create message entries in a similar way tothe folder entry from Recipe 4.4.5.2, but the client MTM you are usingshould have a CreateMessageL() function which will do the work foryou; for instance, it sets the protocol-specific message settings such asthe service center address for SMS, and sets at least iType and iMtm tomake the entry valid.

This is recommended because it reduces the chanceof leaving something out or making a mistake; however, be aware thatthis is a synchronous function, so if you are using it repeatedly (as in ourapplication) you should wrap it in an active object and make sure thatthe RunL() can complete relatively quickly.Again, we do not create a new CSmsClientMtm object, but store areference to the one owned by CSmsManager (and the same idea is usedthroughout the recipes). We reuse iOperation and iFolderHeaderfrom Recipe 4.4.5.2.#include <smsclnt.h> // CSmsClientMtm#include <msvapi.h> // CMsvOperation_LIT(KExampleRecipientAddress, "+440123456789");class CSmsCreator : public CActive{public:void CreateMessageEntriesL(TRequestStatus& aStatus);private:void CreateMessageL();private:CSmsClientMtm& iSmsMtm;};To initialize the message creation, CreateMessageEntriesL()sets the context of the SMS client MTM to the folder entry from Recipe4.4.5.2 (this is the parent entry for our new message).MESSAGING183void CSmsCreator::CreateMessageEntriesL(TRequestStatus& aStatus){...iSmsMtm.SwitchCurrentEntryL(iFolderHeader.Id());...}The actual message creation takes place in our CreateMessageL()function, using the function of the same name in the SMS client MTM.We retrieve the TMsvEntry of the new message entry in order to pushit to the entry cleanup stack so that it will be removed if something goeswrong; we then retrieve the body of the message and insert some text.Next we add a message recipient address; this is also the time to addattachments, set the subject or change any other settings for the entrywhich are relevant to the type of message you are using.

We can callthe client MTM’s ValidateMessage() function to validate the addressformat – the implementation of this function is dependent on the MTMyou are using.Finally, we call CSmsClientMtm::SaveMessageL() to committhe changes (this also updates the Visible and InPreparationattributes), and pop the message from the entry cleanup stack.#include <txtrich.h> // CRichText#include <mtmdef.h> // TMsvPartList, KMsvMessagePartRecipientvoid CSmsCreator::CreateMessageL(){iSmsMtm.CreateMessageL(0);TMsvEntry header = iSmsMtm.Entry().Entry();iSmsMtm.Session().CleanupEntryPushL(header.Id());CRichText& body = iSmsMtm.Body();// Create some body text in a descriptor...body.InsertL(0, bodyText);iSmsMtm.AddAddresseeL(KExampleRecipientAddress);User::LeaveIfError(iSmsMtm.ValidateMessage(KMsvMessagePartRecipient));header.SetUnread(ETrue);iSmsMtm.SaveMessageL(); // sets visible and not in preparationiSmsMtm.Session().CleanupEntryPop(1);}4.4.5.4Read Message DetailsAmount of time required: 10 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): smsclnt.h, msvstd.h, msvids.hRequired platform security capability(s): Platform-dependent (seeexample code)184SYMBIAN C++ RECIPESProblem: You want to display a summary of an unread message.Solution: We set our CMsvEntry to point to our folder entry in orderto find the child entry we are interested in.

We retrieve the messagedescription and details from the header metadata using the TMsvEntryclass.Description: Our application reads data for a number of messages, so, justas for Recipe 4.4.5.3, we wrap the reads in a long-running active object.CMsvEntrySelection is an array of TMsvId values – an object of thistype is often returned from, or passed to, messaging functions.#include <smsclnt.h> // CSmsClientMtm#include <msvstd.h> // CMsvEntrySelectionclass CSmsReader : public CActive{public:void DisplayUnreadMessageSummariesL(TMsvId aFolderId,TRequestStatus& aStatus);private:void InitializeL(TMsvId aFolderId, TRequestStatus& aStatus);void DisplayMessageSummaryL();private:CMsvEntry& iEntry;CMsvEntrySelection* iMessages;TInt iMessageCount;TInt iCounter;};DisplayUnreadMessageSummariesL() calls InitializeL()which sets iEntry to our example folder and retrieves the list of childrenof type SMS, using ChildrenWithMtmL(), clearing the New flag forthese messages.#include <msvids.h> // TMsvIds for common foldersvoid CSmsReader::InitializeL(TMsvId aFolderId, TRequestStatus& aStatus){if (aFolderId != KMsvNullIndexEntryId){iEntry.SetEntryL(aFolderId);iMessages = iEntry.ChildrenWithMtmL(KUidMsgTypeSMS);iMessageCount = iMessages->Count();if (iMessageCount > 0){iEntry.ChangeAttributesL(*iMessages, 0, KMsvNewAttribute);}}}MESSAGING185We set iEntry to point to the message we want to read and checkthat the message is unread (we set this attribute when we created or editedthe message).

If so, we display the message description and details. Themeaning of these depends on message type: for SMS, iDescriptionis the beginning of the message, disregarding leading white space (thelength of which is given by the DescriptionLength() setting in theSMS settings) and iDetails is the address of the first recipient. For othermessage types, see the documentation in the OS Library, for exampleSymbian OS Guide Messaging Using email TMsvEntry functionsand members used in SMTP message entries. To finish, we update theUnread flag.void CSmsReader::DisplayMessageSummaryL(){iEntry.SetEntryL(iMessages->At(iCounter ));TMsvEntry header = iEntry.Entry();if (header.Unread()){DisplayInfo(header.iDescription);DisplayInfo(header.iDetails);header.SetUnread(EFalse);iEntry.ChangeL(header );}...}4.4.5.5Edit a MessageAmount of time required: 10 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.lib, etext.libRequired header file(s): smsclnt.h, msvids.h, txtrich.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to edit aspects of a message such as the body textand the addressee list.Solution: We use the client MTM to add an addressee, edit body text andsave the changes.Description: The EditMessageL() function calls the Initialize()function and then uses the CSmsClientMtm class to edit the message asdescribed.#include <smsclnt.h> // CSmsClientMtm_LIT(KExampleSmsBodyTextExtension,"This text extends the SMS message text.

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

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

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

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