Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 21

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 21 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 212018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

If the user clicks theSelect key, the laser beam is activated by setting the global variableshoot = True.The game code ends with the event loop. The pad is advanced theamount determined by the constant PAD SPEED, however keeping itwithin the screen limits. After this, status of the UFOs is updated. Then110SOUND, INTERACTIVE GRAPHICS AND CAMERAthe screen is re-drawn and the frame is paused on screen for a sleepfraction of a second.

The e32.ao sleep() function lets any new userevents, such as key presses, be processed during the pause. Finally, thetime counter, timer, is incremented by one and the event loop startsagain from the beginning.This example, besides being a highly addictive game, introduced several useful concepts that can be re-used in many game-like applications.As a further exercise, you might want to add background music and soundeffects to make the game even more engaging.

Creating a high-score listmight not be a bad idea, especially after you have read Chapter 6, whichexplains how to load and save data.5.6 SummaryIn this chapter we first showed how to program applications to play andrecord sounds in various formats. Then, we described three approachesto programming keyboard keys and we outlined how to draw graphicsprimitives to the screen, with other useful features of the graphicsmodule.

We introduced the basic functionalities of the phone’s internalcamera and showed the basic principles of making simple games.We hope you are inspired by the plethora of features that PyS60offers regarding sound, camera and interactive graphics. In this chapter,we introduced each of these features separately, using rather simplistic,but hopefully illustrative examples.

However, in reality, we think thesefeatures are best served as an unprecedented, rich and smooth mixture,preferably combined with other ingredients that are described in thefollowing chapters.6Data HandlingWhen building applications, sooner or later you will come to the pointwhere you want to store some user settings, log data, videos, music,or image files to the phone. This chapter gives you an introduction tohandling data like this. As you will see, PyS60 is quite flexible and easyto use in this regard.Nowadays, data persistence is often handled on the server side.

Thinkof Google GMail, Flickr or the contact list in Skype – all these servicesensure that your information moves with you even though you may accessthe services from various physical devices. Backups, scalability and dataaggregation are easier to handle on the server side than on a single smalldevice. These viewpoints should encourage you to think about storing datain unorthodox ways when programming mobile applications with PyS60.In many cases, sending data to a server is easier than saving it locally.In some cases, saving data locally is the only sensible option.

Youshould be able to save photos, sounds or log events without a networkconnection. You may need a local configuration file to specify how tosetup a network connection in the first place. And since mobile networksmay be unreliable and often have low bandwidth, caching informationlocally can be vital.This is where the lessons of this chapter prove useful.

First, inSection 6.1, we explain where files can be loaded and saved on theS60 platform. We introduce the File object that handles reading andwriting of files. In Section 6.2, we present a slightly different approach thatis based on the phone’s built-in database engine. Then, in Section 6.3,we present a brief overview of current positioning techniques and how touse them in PyS60.To show how to apply these techniques in practice, this chapterincludes two useful applications: in Section 6.3, we build an applicationthat tracks your location based on GSM cell IDs, which demonstratesfile access and a positioning technique. Finally, in Section 6.5, we show112DATA HANDLINGhow you can combine the camera, a sound recorder and some text inputdialogs to create your own vocabulary-learning tool for your next holidayin a foreign country.This chapter also includes two important Python language lessons:one about exception handling and the other about a data structure calleddictionary.6.1 File BasicsFiles on your Symbian device are organized in a hierarchical manner asdrives and directories, similarly to a typical Windows system.

The driveletters refer to the following resources:•C: internal memory of your device•D: operating memory space or RAM (read-only)•E: memory card•Z: fixed memory space or ROM (read-only).You don’t need to worry about drives D: and Z: since they are used bythe operating system only. Starting with Symbian OS v9.0 (3rd Edition ofS60), the directory hierarchy within the drives is strictly defined and onlypartly accessible to your program – see Appendix A for details.Many examples in this book save their files to the memory card, thatis, to the E: drive. If you do not have a memory card, you should changethe drive letter to C:.If your application must save anything to a file, such as private data,photos or sounds, it is polite to place the file in a logical place and try toavoid cluttering arbitrary directories unnecessarily.If a file, typically a photo or a sound, should be visible to thestandard Gallery or to other applications, including the Nokia PC Suitefile manager, the standard C:\Images or C:\Sounds directories, or thecorresponding locations on the E: drive, are appropriate choices.If a file is private to your application and does not have to be visibleto the user or any other application, you should make a private directoryeither under C:\Data or E:\Data.The standard directories E:\Images and E:\Sounds are created bythe built-in camera application and sound recorder, when you save aphoto or a sound to the memory card for the first time.

Thus, thesedirectories are often already available for your application.In contrast, any specific directory for your application has to be createdbefore any files can be saved. The module os provides the functionos.makedirs() that is used to create directories (see Example 40).FILE BASICS113Example 40: Creating a directory for application dataimport os, os.pathPATH = u"C:\\Data\\MyApp"if not os.path.exists(PATH):os.makedirs(PATH)We need to check that the directory does not exist before calling os.makedirs(), as it would throw an exception if the directoryexisted.6.1.1 Handling Error ConditionsEspecially when handling files, Bluetooth and network connections inthe following chapters, exceptions are common.

Often, you can designyour program so that, say, a missing file or an already existing one do notcause a fatal error. Instead, your program could detect the situation andact accordingly.It is not always possible or practical to detect the situation beforehand,as we did with the os.path.exists() function above. However,the program could react to the situation after an exception has occurred.Python provides a mechanism to detect and handle exceptional situationslike this, which is introduced in the language lesson.Python Language Lesson: catching exceptionsIn Python, error conditions are objects, too. Whenever somethingunexpected happens, for example, you try to use a return value of adialog even though it is None, an Exception object is created.

Youcan create exceptions of your own in the following way:raise Exception("I am exceptional")If the exception is not handled by the program, it is shown on theconsole and execution of the program may terminate.However, some exceptions are not really exceptional. For example,we know that trying to play a sound that does not exist will fail. Itmakes sense to prepare for exceptions like this. Exceptions are handledby enclosing suspicious actions between try and except statements,as in the following:114DATA HANDLINGimport appuifwtry:d = appuifw.query(u"Type a word", "text")appuifw.note(u"The word was: "+ word)except:appuifw.note(u"Invalid word", "error")If you type a word in the first dialog, everything works fine. However, if you click ‘Cancel’, an exception is raised since you cannotconcatenate None to a string.

This exception is handled inside theexcept block – in this case, an error dialog is shown.To summarize, if you know that some operations are likely tocause exceptions and you know how to recover from them, place thesuspicious operations between try and except statements and placealternative code in the except block.However, use these statements sparingly, since they may also catchand hide exceptions that are caused by real errors in your program. Thebest approach would be to capture only specific types of exception,instead of all exceptions as we did above. See Python documentationfor more information about this possibility.Note that, because of space constraints, examples in this book do notalways contain the try–except block around critical operations, eventhough using one might make sense. Feel free to make the examples morerobust by adding more exception handlers that take care of possible errorconditions properly.6.1.2File ObjectIn Python, files are read and written through the File object.

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

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

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

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