Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 40

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 40 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 402018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

After CompleteSelf() has finished, the object is ready torun and, providing the active scheduler doesn’t have a higher-priorityobject to dispatch, it calls the RunL() function.const TUint KMaxNumberOfIterationsBeforeRestarting = 80;void CFibonacciGenerator::RunL(){// Update the number of numbers we have generated so far++iSequenceNumber;// Declare calculation result variableTUint64 result = 0;switch(iSequenceNumber){case 1:result = iOldestResult;break;case 2:result = iMostRecentResult;break;default:result = iOldestResult + iMostRecentResult;break;}}// Inform result handler about the next numberiResultHandler.HandleFibonacciResultL(result);if (iSequenceNumber > KMaxNumberOfIterationsBeforeRestarting){// Restart from the beginning once the numbers get very large...Reset();}else if (iSequenceNumber > 2){// Update state for next time aroundiOldestResult = iMostRecentResult;iMostRecentResult = result;}// Request next call to RunL()CompleteSelf();}This function is a bit longer than our earlier examples, so let’s break itup into sections.• First, we’re keeping track of how many numbers we have generated inthe overall sequence.

The main purpose of this is to ensure we can tellwhen we have generated the third (or greater) number and when we’vegenerated a total of 80 numbers. The first two numbers in the sequenceare always 0 and 1 so we do not actually calculate them. However, forLONG-RUNNING TASKS AND ACTIVE OBJECTS199the sequence to be complete, we must make sure we inform the resulthandler about their values before we begin calculating subsequentnumbers, hence we increase the iSequenceNumber counter valueeach time we successfully ‘calculate’ a number.• Next we declare a local variable, result, to hold our calculatedvalue. We then switch on the value of our iSequenceNumbercounter.

If RunL() has only been called once, then we must reportthe iOldestResult (zero) to the result handler. If RunL() hasbeen called twice, we must report the iMostRecentResult (one)to the calculation handler. For any call to RunL() greater thantwo, we use the default case and calculate a real value by addingiMostRecentResult and iOldestResult.• After calculating the next number in the sequence, we must inform ourresult handler what the number was.

Using our mixin interface, wecall iResultHandler.HandleFibonacciResultL() and passthe variable result as an argument. The implementation of theMFibonacciResultHandler class is the main view, and it thenupdates the screen with the result of the calculation. Note that the callis a leaving function.

This means we must expect that the call to thecalculation handler may leave so we must cope with this eventualityby implementing a RunError() function.• Assuming that the result handler does not leave, the next actiondepends on how many numbers in the sequence we have calculated so far. If we have reached 80 numbers, we call Reset() tostart the process again from the beginning. For sequence numbersgreater than two, we must update the iMostRecentResult andiOldestResult variables. We always discard the oldest number,so it is replaced with the value from the previous time RunL() wascalled.

We then update iMostRecentResult with the value wejust calculated.• Finally, since this object is going to continue to calculate the nextnumber in the sequence until it is cancelled, we call the CompleteSelf() function once again.The DoCancel() function is straightforward since we completedour request immediately from within both Start() and RunL(). Therequest status should only be completed once, so there is nothing morefor us to do here.void CFibonacciGenerator::DoCancel(){}200ACTIVE OBJECTSFinally, we must attempt to cope with the possibility that RunL()may leave. As is good practice for all active objects, we implementRunError():TInt CFibonacciGenerator::RunError(TInt aError){Reset();return KErrNone;}In the case of an error, we reset our internal state back to its default values and indicate that we have handled the leave by returning KErrNoneto the active scheduler.You’ll notice here that we didn’t hard-code our RunL() method towrite directly to the screen or display an information message.

Insteadwe chose to add more flexibility to our class by using an interface tohandle the result of the calculation. In this way, we could create differentimplementations of the MFibonacciResultHandler class that behavein different ways, depending on the output type. You’ll see this pattern alot when working with active objects, particularly in the UI framework,since it abstracts the complexity of the active objects.Since our active object had a priority of EPriorityIdle, it doesn’tprevent the other active objects that run within the application’s threadfrom being dispatched. This means it is still possible for the applicationto handle user input, such as displaying a menu, whilst the calculation isgoing on in the background.

This object’s RunL() processing is very fastand, even though it is active all of the time, it doesn’t cause a significantdelay to the dispatch of higher-priority objects. However, this kind ofalways-active object quickly drains the device’s battery if left running fora long time since it prevents the CPU from going to sleep.SummarySymbian OS has a highly responsive pre-emptive multi-threaded architecture. However, most application and server tasks are by nature eventhandlers and active objects are a very suitable paradigm with which tohandle events.Because they are non-pre-emptive, it’s very easy to program withactive objects: you do not need to code mutual exclusion with otherthreads trying to access the same resources.Active objects also use fewer system resources than full-blown threads:by default, thread overheads start at around 4 KB on the kernel side and8 KB on the user side for just the thread’s stacks, whereas active objectsneed be only a few bytes in size.

Additionally, switching between activeSUMMARY201objects is much cheaper than switching between threads, even in thesame process. The time difference can be up to a factor of 10.This combination of ease of use and low resource requirement is amajor factor in the overall efficiency of Symbian OS. However, performance can be impaired if there are many active objects since the activescheduler needs to iterate through the list of active objects to find whichobject’s RunL() to call.7Files and the File SystemThis chapter provides an overview of a range of file-related topics, fromthe file system itself to resource and bitmap files.

With such a wide rangeof topics, it isn’t possible to give a detailed description. The intention,instead, is to provide the essential information, with some practicalexamples that allow you to start making effective use of the system.7.1 File-Based ApplicationsAlmost all applications use files for data storage. The way files are useddepends on the data the application needs to save to persistent memory.• A Jotter application is clearly file-based. You can save textual datainto a file and load data from a file to display.• A simple game allows you to save your current status and resumeplaying at some later time. The status information may not be complicated and is discarded once the player has resumed playing or savesthe game again after some progress.• An application such as a calendar is file-based, but you don’t loadand save the whole file at once.

Instead, you use the file as a databaseand load and save individual entries. For efficiency, you also maintainsome index data in RAM (for example, on the C: drive). This indexmay or may not be saved to file as well.• An application such as Messaging is again file-based, making use ofdatabase files where appropriate and separate data files for contentdata such as text and attachments. However, it saves attachment datato media and relies on another application, such as a photo viewer,to read photo data.204FILES AND THE FILE SYSTEMRAMJotterCalendarJotter object(real)saveloadFileIndicesscanEntryloadsaveCalendar database (real)DiskFigure 7.1File and database applicationsFigure 7.1 illustrates the difference between file and database applications.In load–save applications, we tend to think that the ‘real’ data is inRAM: the file is just a saved version of the real data created or edited bythe application.

In database applications, we tend to think that the ‘real’document is the database: each entry is just a RAM copy of something inthe database. The disciplines for managing the documents are thereforequite different.7.2 Drives and File TypesFrom the perspective of the Symbian OS phone user, there are usuallytwo types of file:• document files contain the end-user’s data• system files are mainly stored in the phone’s ROM image (theZ: drive).For most end users, it is better to pretend that there is only one typeof file – document files – and hide the system files altogether.

In SymbianOS phones, the user is not exposed to files directly; if it is possible tobrowse files with a file manager application, system drives are typicallyhidden. Most user data files are browsed via the application that presentsthe data to the user.FILE SYSTEM SERVICES205The drive configuration of a Symbian OS phone may vary from deviceto device. Feature phones may have large drives for storing music orvideo data. Some devices have drives that are accessible using USB Massstorage via a host computer. The underlying media and file-system typeassigned to a particular drive letter is specific to the UI and device.However, some details are consistent across all phone devices: driveZ: is the ROM drive; it contains binaries and system resource files thatconsist of the operating system and its preinstalled applications.Symbian OS v9 introduced platform security, which has several implications for the use of files and file systems when developing applications.The concept of data caging, a key part of platform security, allows eachapplication to own a private directory.

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

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

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

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