Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 30

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 30 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 302018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Becauseof the symmetrical nature of the background image the effect is to simulatean infinitely scrolling background (see Figure 3.17).To observe the full effect, download and run the example. The sourcecode and JAR and JAD files for the LayerManagerDemo MIDlet areavailable from the Symbian website at www.symbian.com/books.The DemoRacer case study, discussed in Chapter 5, provides a further detailed study of programming the Game API, including usingcollision detection.Figure 3.17 The LayerManagerDemo MIDlet.MIDP 2.01453.3.8 The Media APIAs mentioned in Chapter 2, MIDP 2.0 introduces support for audioplayback and sound generation in two new packages:• javax.microedition.media• javax.microedition.media.control.Specifically, the Media API mandates support for tone generation andaudio playback of WAV files.

Support for other audio formats is optional.Symbian’s MIDP 2.0 Media API implementation, at the time of writing,does not provide support for additional optional audio formats. However,licensee phones built on Symbian OS may provide support for additionalaudio formats, particularly if they provide implementations of the fullMobile Media API (JSR 135), such as found on the Series 60 Nokia 6600.The MIDP 2.0 Media API is an audio-only building block subset of theMobile Media API that is fully upward compatible with the Mobile MediaAPI. The rationale behind providing only audio support in the Media APIwas that the MIDP 2.0 specification is targeted at the whole spectrum ofmobile phones including mass-market low-end phones with no supportfor video rendering capabilities.

In contrast, the optional Mobile MediaAPI is targeted at high-end feature phones and PDAs with advancedsound and video capabilities.Since the Media API is a proper subset of the Mobile Media API weshall leave a detailed discussion of programming tone generation andaudio playback to later in the chapter where a section is devoted to theMobile Media API.3.3.9 Other New Features3.3.9.1 MIDlet ClassMIDP 2.0 brings a couple of new methods into the MIDlet class includingthe platformRequest() method:public final boolean platformRequest(String URL)This method allows the MIDlet to bring certain native applicationsto the foreground and permits the user to interact with the context whilethe MIDlet continues running in the background.

Forms of the StringURL argument required by the MIDP 2.0 specification include:platformRequest("www.symbian.com/mobile/MyMidlet.jad")or:platformRequest("tel:07940176427")146MIDP 2.0 AND THE JTWIThe former launches the installer to install the indicated MIDletsuite. The latter launches the native phone application, if supported bythe device. If the platform cannot handle the specified URL request aConnectionNotFoundException will be thrown.

Note that at thetime of writing platformRequest() was not supported on the currentfirmware release (3.42.1) available on the Nokia 6600. Later versions ofthe firmware will support this feature (see Known Issues in the Nokia6600 MIDP 2.0 Implementation Version 1.2 at www.forum.nokia.com).Another new method introduced in MIDP 2.0 is the checkPermission() method.public final int checkPermission(String permission)This allows the MIDlet to check the permission of a particular API,passed in as the permission argument.

For example, the code shownbelow would check the permission to open an SMS connection.checkPermission(“javax.microedition.io.Connector.sms”)The return value can be:• 1 – if the permission is Allowed• 0 – if the permission is denied (including when the API is not supportedon the device)• −1 – if the permission is unknown, including the case where thepermission requires user interaction.3.3.9.2 Alpha BlendingMIDP 2.0 adds functionality to the Image and Graphics classes toprovide support for alpha blending.

Alpha blending is a way of combininga semi-transparent mask image with a background image to create ablended image with the appearance of transparency. The degree oftransparency depends on the alpha coefficient. The alpha coefficient cantake a value ranging from 0, in which case the mask is totally transparentand the blended image is simply the background image, to 1 (FF) in whichcase the mask is completely opaque and therefore the blended image isthe same as the mask image.In particular, MIDP 2.0 provides the createRGBImage() method ofthe Image class, which allows an image to be created from an array ofARGB values:public static Image createRGBImage(int[] rgb, int width, int height,boolean processAlpha)MIDP 2.0147Figure 3.18 Illustrating the drawRGB() method.The rgb argument represents the image data consisting of an arrayof 32-bit values of the form 0xAARRGGBB. The high eight bits of each32-bit value provide the value of the alpha coefficient and the remaining24 bits represent the 8-bit RGB values.

The alpha value is used in alphablending. The width and height arguments represent the width andthe height of the image in pixels. If the processAlpha argument is false,alpha blending is disabled and the image will appear totally opaque.MIDP 2.0 also adds the drawRGB() method to the Graphics class:public void drawRGB(int[] rgbData, int offset, int scanlength,int x, int y, int width, int height, boolean processAlpha)The rgbData argument is presented in 0xAARRGGBB format, aspreviously. The offset argument represents the array index of the firstvalue to be drawn and scanlength represents the relative offset in thergbData array between corresponding pixels in consecutive rows.

Forinstance, let us consider an array of 32 ARGB values representing animage 8 pixels wide and 4 pixels high. However, we only want to renderpixels corresponding to a central strip of an image 4 pixels wide and 4pixels high (see Figure 3.18).In this case we would invoke the drawRGB() method with the offsetvalue set to 2 and the scanlength equal to 8. The values for widthand height are both equal to 4 in this case.Let us now consider an example of alpha blending in action. TheAlphaCanvas class shown below uses alpha blending to progressivelyrender a semi-transparent red mask over a background image:importimportimportpublicjavax.microedition.midlet.*;javax.microedition.lcdui.*;java.io.*;class AlphaCanvas extends Canvas implements Runnable {private Image backgroundImage;private int[] maskArray;private int imageWidth;private int imageHeight;private int x;private int y;private int maskHeight = 0;public AlphaCanvas(String imageName) {148MIDP 2.0 AND THE JTWI//create the background imagetry {backgroundImage = Image.createImage(imageName);}catch(IOException ioe) {ioe.printStackTrace() ;}imageWidth = backgroundImage.getWidth();imageHeight = backgroundImage.getHeight();//create a semi-transparent red mask to cover the//background imagemaskArray = new int[imageWidth*imageHeight];for (int i = 0; i < imageWidth*imageHeight; i++) {maskArray[i] = 0x80FF0000;//alpha coefficient set to 0.5}x = (getWidth() – imageWidth)/2;y = (getHeight() – imageHeight)/2;}public void paint(Graphics g) {g.drawImage(backgroundImage, x, y,Graphics.TOP|Graphics.LEFT);//render the semi-transparent maskif (maskHeight != 0){g.drawRGB(maskArray, 0, imageWidth, x, y, imageWidth,maskHeight, true);}}public void run() {for(int i = 1; i <= imageHeight; i++) {maskHeight = i;repaint();try {Thread.sleep(50);}catch(InterruptedException ie) {}}}}A background image is created from a resource file in the AlphaCanvas constructor.

We then create a data array containing a sufficientnumber of values to completely mask the background image:maskArray = new int[imageWidth*imageHeight];for (int i = 0; i < imageWidth*imageHeight; i++) {maskArray[i] = 0x80FF0000;//alpha coefficient set to 0.5}In this case the alpha coefficient is set to 0.5 (0 × 80). The paint()method first renders the background image and then the mask using thedrawRGB() method:g.drawRGB(maskArray, 0, imageWidth, x, y, imageWidth, maskHeight,true);MIDP 2.0149Figure 3.19 Alpha blending on a Nokia 6600.As we want to render over the full width of the background image,the offset value is set to 0 and the scanlength is equal to the widthof the background image.

By successively incrementing the mask heightand calling repaint() we are able to gradually cover the backgroundimage with the transparency. Figure 3.19 displays screenshots of theAlphaBlending MIDlet running on a Nokia 6600.The full source code for the AlphaBlending MIDlet can be downloadedfrom Symbian’s website at www.symbian.com/books.3.3.9.3 RMS StorageThe Record Management System (RMS) storage mechanism was introduced in Chapter 2. We will now investigate it in more detail.

The RMSprovides simple record-based persistent storage, with data stored as arecord in the form of a byte array. The MIDP 1.0 specification requiredthat a record store created by a MIDlet can only be accessed by a differentMIDlet if both MIDlets belonged to the same MIDlet suite. The MIDP 2.0specification has relaxed this restriction, allowing any MIDlet to accessanother MIDlet’s record store provided that the MIDlet that created therecord store has given authorization.To use the RMS, we must first open a record store using one of theoverloaded openRecordStore() methods:public static RecordStore openRecordStore(String recordStoreName,boolean createIfNecessary)public static RecordStore openRecordStore(String recordStoreName,boolean createIfNecessary, int authmode, boolean writable)150MIDP 2.0 AND THE JTWIpublic static RecordStore openRecordStore(String recordStoreName,String vendorName, String suiteName)The last two methods were added by the MIDP 2.0 specification.

Thesecond openRecordStore() method takes an authmode argumentthat can have one of two possible public static final int values:AUTHMODE_ANY and AUTHMODE_PRIVATE.AUTHMODE_ANY allows the RecordStore to be accessed by anyMIDlet in any MIDlet suite while AUTHMODE_PRIVATE restricts accessonly to MIDlets in the same suite as the creator of the RecordStore.If writable is true, MIDlets in other suites that have been grantedaccess can write to this RecordStore.The third openRecordstore() method is used to open a RecordStore associated with the MIDlet suite that is identified bythe suiteName argument.

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

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

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

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