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

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

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

");_LIT(KExampleRecipientAddress2, "+449876543210");186SYMBIAN C++ RECIPESclass CSmsEditor : public CBase{public:void EditMessageL(TMsvId aFolderId);private:void InitializeL(TMsvId aFolderId);private:CSmsClientMtm& iSmsMtm;};To initialize, we retrieve the child entries of the folder as for Recipe4.4.5.4, only this time using CSmsClientMtm instead of CMsvEntry.In this case, the client MTM class is preferable, as we need to use it later.void CSmsEditor::InitializeL(TMsvId aFolderId){if (aFolderId != KMsvNullIndexEntryId){iSmsMtm.SwitchCurrentEntryL(aFolderId);CMsvEntrySelection* selection = iSmsMtm.Entry().ChildrenWithMtmL(KUidMsgTypeSMS);CleanupStack::PushL(selection);if (selection->Count() > 0){iSmsMtm.SwitchCurrentEntryL(selection->At(0));iSmsMtm.LoadMessageL();}CleanupStack::PopAndDestroy(selection);}...}After initializing, we add another addressee and validate the addressformat, just as in Recipe 4.4.5.3.

We then retrieve the body text ofthe message using the client MTM’s Body() function in order to insertanother line. We set the message Unread attribute to true (so that thechanges may be picked up by the SMS reader) and save the changes.void CSmsEditor::EditMessageL(TMsvId aFolderId){InitializeL(aFolderId);iSmsMtm.AddAddresseeL(KExampleRecipientAddress2);User::LeaveIfError(iSmsMtm.ValidateMessage(KMsvMessagePartRecipient));CRichText& body = iSmsMtm.Body();body.InsertL(0, KExampleSmsBodyTextExtension);TMsvEntry header = iSmsMtm.Entry().Entry();header.SetUnread(ETrue);iSmsMtm.SaveMessageL();}MESSAGING4.4.5.6187Retrieve and Edit Message SettingsAmount of time required: 15 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): smsclnt.h, csmsaccount.h, smutset.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to edit settings common to all SMS messages, such asthe length of the description.Solution: We use the CSmsAccount class to access the CSmsSettings,which is the interface to allow us to edit the SMS settings.Description: The CSmsAccount and CSmsSettings classes allow us toaccess the account information and settings which are stored in the CentralRepository.

For email, the equivalent classes are CEmailAccounts,CImPop3Settings, CImImap4Settings and CImSmtpSettings,and for MMS they are CMmsAccounts and CMmsSettings.#include <smsclnt.h>class CSmsEditor : public CBase{public:void EditSettingsL();// same as the Edit a Message recipe...};It is simple to edit the settings – we create a CSmsAccount and loadthe settings into a CSmsSettings object. We can then retrieve andedit settings such as the description length, and must call CSmsAccount::SaveSettingsL() to commit the changes.#include <csmsaccount.h> // CSmsAccount#include <smutset.h> // CSmsSettingsvoid CSmsEditor::EditSettingsL( ){CSmsAccount* smsAccount = CSmsAccount::NewLC();CSmsSettings* smsSettings = CSmsSettings::NewLC();smsAccount->LoadSettingsL(*smsSettings);TInt descriptionLength = smsSettings->DescriptionLength();smsSettings->SetDescriptionLength(descriptionLength + 40);smsAccount->SaveSettingsL(*smsSettings);CleanupStack::PopAndDestroy(2, smsAccount); // smsSettings, smsAccount}1884.4.5.7SYMBIAN C++ RECIPESCopy a MessageAmount of time required: 15 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): msvapi.h, smsclnt.h, smut.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to create a copy of a message.Solution: Use the CMsvEntry::CopyL() function.Description: CopyMessageL() calls Initialize() and then uses theasynchronous version of CopyL() to create a copy of a message in thedraft folder.

We therefore make the CSmsTransporter class an activeobject.#include <msvapi.h> // CMsvOperation#include <smsclnt.h> // CSmsClientMtmclass CSmsTransporter : public CActive{public:void CopyMessageL(TMsvId aFolderId, TRequestStatus& aStatus);private:void InitializeL(TMsvId aFolderId, TRequestStatus& aStatus);private:CSmsClientMtm& iSmsMtm;CMsvOperation* iOperation;TMsvId iMessageId;};As in Recipe 4.4.5.5, we find a message entry by enumerating the childentries of our folder (this is done using the client MTM but could equallybe done using CMsvEntry). In this case, we only need the TMsvId ofthe message in order to copy it.#include <msvids.h> // TMsvIds for standard folders#include <smut.h> // KUidMsgTypeSMSvoid CSmsTransporter::InitializeL(TMsvId aFolderId,TRequestStatus& aStatus){...if (aFolderId != KMsvNullIndexEntryId){iSmsMtm.SwitchCurrentEntryL(aFolderId);CMsvEntrySelection* selection = iSmsMtm.Entry().ChildrenWithMtmL(KUidMsgTypeSMS);if (selection->Count() > 0){MESSAGING189iMessageId = selection->At(0);}delete selection;}...}We then call CMsvEntry::CopyL() and SetActive() to initiatethe asynchronous copy.

Note that there is also an overload of CopyL()which takes a CMsvEntrySelection array of entry IDs. When copyingis complete, the RunL() function is called, in which we check the valueof iStatus.void CSmsTransporter::CopyMessageL(TMsvId aFolderId,TRequestStatus& aStatus){InitializeL(aFolderId, aStatus);iOperation = iSmsMtm.Entry().CopyL(iMessageId,KMsvDraftEntryId, iStatus);...SetActive();}Whether a copy operation can involve two remote entries is dependenton the MTM.4.4.5.8Move a MessageAmount of time required: 15 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): msvapi.h, msvids.h, smsclnt.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to move a message to another folder.Solution: Use the CMsvEntry::MoveL() function.Description: MoveMessageL() calls Initialize(), exactly as inRecipe 4.4.5.7, and then uses the asynchronous version of MoveL()to move a message to the global outbox.#include <msvapi.h> // CMsvOperation#include <smsclnt.h> // CSmsClientMtmclass CSmsTransporter : public CActive{public:...void MoveMessageL(TMsvId aFolderId, TRequestStatus& aStatus );190SYMBIAN C++ RECIPES// same as the Copy a Message recipe...};We then call CMsvEntry::MoveL() and SetActive() to initiatethe asynchronous move.

Again, there is also an overload of MoveL()which takes a CMsvEntrySelection array of entry IDs. When movingis complete, the RunL() function is called, in which we check the valueof iStatus.void CSmsTransporter::MoveMessageL(TMsvId aFolderId,TRequestStatus& aStatus){InitializeL(aFolderId, aStatus);iOperation = iSmsMtm.Entry().MoveL(iMessageId,KMsvGlobalOutBoxIndexEntryId, iStatus);...SetActive();}Whether a move operation can involve two remote entries is dependenton the MTM.4.4.5.9Send a MessageAmount of time required: 15 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): msvapi.h, smsclnt.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to send a message.Solution: Use the CMsvEntry::CopyL() function to copy the messageto the remote service which is responsible for the type of message youare using.Description: This is very similar to the copy functionality in Recipe4.4.5.7, except that the target ID is the TMsvId of the remote serviceentry.#include <msvapi.h> // CMsvOperation#include <smsclnt.h> // CSmsClientMtmclass CSmsTransporter : public CActive{public:MESSAGING191void SendMessageL(TMsvId aFolderId, TRequestStatus& aStatus);// same as the Copy a Message recipe...};Initialize() is the same as in Recipe 4.4.5.7.void CSmsTransporter::SendMessageL(TMsvId aFolderId,TRequestStatus& aStatus){InitializeL(aFolderId, aStatus);TMsvId smsServiceId = iSmsMtm.ServiceId();iOperation = iSmsMtm.Entry().CopyL(iMessageId,smsServiceId, iStatus);...SetActive();}It is also possible to use CMsvEntry::MoveL() to send a message –the difference is that the message will be deleted from the local store afterthe message is sent.When the SMS or IMAP4 MTM is sending a message, it checks thevalue of TMsvEntry::SendingState() for all the other messages ofthe same type in the outbox.

The result will be one of the values inTMsvSendState; if it is KMsvSendStateWaiting, KMsvSendStateUponRequest or KMsvSendStateResend, that message will alsobe sent at the same time.Some MTMs support scheduled sending of messages – to activatethis for SMS, use CSmsSettings::SetDelivery(ESmsDeliveryScheduled). To ensure that a particular message will be sent by thescheduler, you must set the sending state of that message to KMsvSendStateScheduled, otherwise the behavior described above will stillapply.4.4.5.10Delete MessagesAmount of time required: 15 minutesLocation of example code: \Messaging\SmsManagerRequired libraries: msgs.lib, smcm.libRequired header file(s): msvapi.h, msvstd.h, msvids.h, smut.hRequired platform security capability(s): Platform-dependent (seeexample code)Problem: You want to delete messages.Solution: Use CMsvEntry::DeleteL().Description: In this case we are not using the client MTM, only CMsvEntry.

There is not much initializing to be done, so there is no separateInitialize() function.192SYMBIAN C++ RECIPES#include <msvapi.h> // CMsvEntry, CMsvOperation#include <msvstd.h> // CMsvEntrySelectionclass CSmsDeleter : public CActive{public:void DeleteMessagesL(CMsvEntry& aEntry, TMsvId aFolderId,TRequestStatus& aStatus);private:CMsvEntrySelection* iSelection;CMsvOperation* iOperation;};In this case, we are deleting all the SMS messages in a folder, whichis a simple task – call CMsvEntry::DeleteL() passing in the CMsvEntrySelection of message IDs and SetActive(). However, it isalso possible to delete just one message, passing in its TMsvId.#include <msvids.h> // TMsvIds for standard folders#include <smut.h> // KUidMsgTypeSMSvoid CSmsDeleter::DeleteMessagesL(CMsvEntry& aEntry, TMsvId aFolderId,TRequestStatus& aStatus){if (aFolderId != KMsvNullIndexEntryId){aEntry.SetEntryL(aFolderId)iSelection = aEntry.ChildrenWithMtmL(KUidMsgTypeSMS);}...iOperation = aEntry.DeleteL(*iSelection, iStatus);SetActive();}4.4.5.11Handle Incoming MessagesAmount of time required: 15 minutesLocation of example code: \Messaging\SmsManagerRequired header file(s): msvapi.h, msvids.h, smsclnt.hRequired libraries: msgs.lib, smcm.libProblem: You want your application to be informed when new messagesare received by the device, or created locally, so that we can handlethese events.Solution: When new entries are created, we are notified by MMsvSessionObserver::HandleSessionEventL().Description: New incoming SMS messages are received automaticallyby an SMS watcher and placed in the global inbox or class 2 folderMESSAGING193(usually the SIM, accessible through the SMS client MTM).

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

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

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

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