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

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

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

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

When creating or editing anentry, the MTM should check to see if it is a service entry or a messageentry and perform the correct action.When SendAs or the Send dialogs scan the capabilities of each MTM tosee if they are appropriate for the Send menu, the capabilities are queriedin the order listed in the table below. The expected response must matchthe table or the MTM will not be listed.FunctionExpected responseQueryCapability() called withKUidMtmQueryCanCreateNewMsgValueETrueCanCreateEntryL()KErrNoneQueryCapability() called withKUidMtmQueryMaxBodySizeValueBody text size. If the bearerhas no size limit thenchoose a suitably largenumber such as KMaxTIntQueryCapability() called withKUidMtmQueryMaxTotalMsgSizeValueTotal size limit includingattachments, again set toKMaxTInt if there is noinherent limit262SENDING MESSAGES9.8.2 Specifying the Send menu textThe default text used in the Send menu is the human readable namefor the MTM as specified in the registration resource file.

This is fine forinitial development purposes, but a localizable string is required for thefinal version of the code.This is achieved by supplying a function with the flag EMtudCommandSendAs in the UI Data MTM resource file and ensuring thatfunctiontext is localized.// MTM-specific function arrayRESOURCE MTUD_FUNCTION_ARRAY r_textud_function_array{functions={MTUD_FUNCTION { functiontext="to Flickr";command=KMtmUiFunctionSendAs; flags=EMtudCommandSendAs;}};}9.9 The Flickr UI MTMThe UI MTM often contains the bulk of the implementation of the fourMTMs.

This is because the UI MTM does a lot of decision making, maysupply a UI for reporting the progress of the client/server MTMs and mustprovide a way of editing the message and the service settings.For complex message types, the editing is usually delegated to aviewer/editor application. The viewer/editor has the hidden attribute setin the AIF file so that it doesn’t show up in the application menu. Theviewer/editor is passed the TMsvId of the newly created message as partof the command line parameters.The FlickrMTM has no editor, it simply puts up a dialog and startsuploading the message to the Flickr website.9.9.1 Editing a messageCMsvOperation* CFlickrMtmUi::EditL(TRequestStatus& aStatus)// Edit{TUid type = iBaseMtm.Entry().Entry().iType;iServiceId = iBaseMtm.Entry().Entry().iServiceId;__ASSERT_DEBUG(type==KUidMsvMessageEntry | |type==KUidMsvServiceEntry,Panic(EFlickrMtmUiWrongEntryType));FLICKR CLIENT MTM263if ( type == KUidMsvMessageEntry ){return MessageEditL(aStatus);}else{return ServiceEditL(aStatus);}}You should check to see if the message is a service or message typein order to perform the correct action.

The Flickr MTM does not supportediting of services.Editing the message causes a CImageUploadOperation to be kickedoff. This is essentially a send operation wrapped up in an ‘Uploading toflickr’ dialog in order to give the user some feedback.CMsvOperation* CFlickrMtmUi::MessageEditL(TRequestStatus& aStatus)// Message editing{aStatus = KRequestPending;CMsvEntry& entry = iBaseMtm.Entry();CImageUploadOperation* op = new(ELeave)CImageUploadOperation(*this,Session(), entry.Entry().Id() , CActive::EPriorityStandard,aStatus);CleanupStack::PushL(op);op->StartL();CleanupStack::Pop(op);return op;}9.10 Flickr Client MTM9.10.1 Message layoutA client MTM dictates how the message store and message entries areused to hold messages.

A single message seen by the user in the inboxcan be composed of many child message entries that store the structure.However, in practice most messages are represented by a single messageentry.The default behavior for an MTM which supports attachments is thatrequests from the clients to add attachment files will be handled automatically by the attachment manager.

The attachment manager associatesfiles with a particular message entry, and allows the MTM to enumerateand access the message.264SENDING MESSAGESPotentially, a Flickr message type could contain further informationsuch as body text containing description, tags and a privacy tag (these arefeatures of the Flickr API), but for this example the Flickr MTM messagepayload can be defined entirely as a single attachment. Only the filenameand the image data are used, which leads to a very simple messagerepresentation.When an MTM is asked to add an attachment, the default behavior(if not overridden by the MTM) is to store the attachment as part of themessage store. The default is acceptable for the Flickr MTM.When a message needs to be sent, the server MTM uses the attachmentmanager API (MMsvAttachmentManager) to retrieve the attachments.Handling a SendAs requestOnce a message has been created, a SendAs client may request themessage be sent immediately.

This is actioned by a call to the clientMTM’s InvokeAsyncFunctionL() with a function UID KMTMStandardFunctionsSendMessage.CMsvOperation* CFlickrMtmClient::InvokeAsyncFunctionL(TInt aFunctionId,const CMsvEntrySelection& aSelection, TDes8& aParameter,TRequestStatus& aCompletionStatus)// Call MTM-specific operation asynchronously{CMsvOperation* operation = NULL;switch (aFunctionId){case KMTMStandardFunctionsSendMessage:{operation = (Entry().Session().TransferCommandL(aSelection,aFunctionId, aParameter, aCompletionStatus));}break;default:__ASSERT_DEBUG(EFalse,gPanic(EFlickrMtmClientCommandNotSupported));break;}return operation;}The client MTM must return an object derived from CMsvOperation– despite the return type, it must not return NULL.9.10.2 Transferring commands from client to serverThe Flickr MTM client MTM delegates the SendAs call to the server MTM.The message server provides a convenient TransferCommandL()to perform the delegation in which a client side CMsvOperation representing the server-side operation is created and acts as a proxy to allowTHE FLICKR SERVER MTM265progress information to flow back from server to the client.

The serveroperation may be cancelled at any time by calling Cancel() on theclient side CMsvOperation.After returning the CMsvOperation from TransferCommandL(),the client MTM has nothing further to do with the transaction andownership of the operation is transferred to the caller of InvokeAsyncFunctionL().9.11 The Flickr Server MTMAs shown in Figure 9.6, the server MTM runs inside the message serverprocess, on the other side of the client/server boundary from the clientMTM. When a TransferCommandL() is called by the client MTM, theserver MTM is invoked via StartCommandL() with parameters fromthe client and a request status which must be completed when the serverMTM has finished its task.The FlickrMTM only supports one command, KMTMStandardFunctionsSendMessage.void CFlickrServerMtm::StartCommandL(CMsvEntrySelection& aSelection,TInt aCommand, const TDesC8& /*aParameter*/, TRequestStatus&aStatus)// Run MTM-specific command on selection of entries// Only command supported is Refresh{AssertIdle(); // Standard check to assert that we are not already busyswitch (aCommand){case KMTMStandardFunctionsSendMessage:{SendToFlickrL(aSelection[0], aStatus);}break;}}9.11.1 The message transportIn general the server MTM provides the message transport – the codewhich actually sends the message over the underlying transport, such asBluetooth, TCP/IP or another protocol.At the point the message server gets hold of the message, it will bestored in the message store by the client side code as a mix of TMsvEntryflags, rich text and/or attachments.Essentially a message transport is responsible for translating or parsingthe message from the format in which it is stored in the message store266SENDING MESSAGESinto one that can be transmitted.

The transport may also change the stateof the message, or perhaps delete it after it has been successfully sent.For the Flickr MTM, the server MTM needs to extract the attachmentfrom the message store and upload the image using the FlickUpload.dllfrom Chapter 11, then delete the message from the outbox.The following code fragment shows how the message is retrieved fromthe TMsvId passed from the client MTM and demonstrates how theattachment is retrieved from the message store.void CFlickrServerMtm::SendToFlickrL(TMsvId aMessage, TRequestStatus&aStatus ){iCurrentOperation = EFlickrSendPhoto;iReportStatus = &aStatus;aStatus = KRequestPending;iServerEntry->SetEntry(aMessage);CMsvStore* store = iServerEntry->ReadStoreL();CleanupStack::PushL(store);MMsvAttachmentManager &attachMan = store->AttachmentManagerL();if( attachMan.AttachmentCount()!= 1 ){User::Leave(KErrNotSupported);}CMsvAttachment* attachMent = attachMan.GetAttachmentInfoL(0);CleanupStack::PushL(attachMent);const TDesC8& mimeType = attachMent->MimeType();iFlickrRestAPI->IssueImagePostL(attachMent->FilePath());CleanupStack::PopAndDestroy(2,store);}Since the code is running in the context of the message server process,it has direct access to the attachment file in the message store, or in thecase of a linked file the file path will point to a public folder, such asc:\data\images in our earlier example.Operations running in a system server such as the message server threadmust be cooperative.

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

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

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

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