JavaME (779880), страница 2

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

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

This is similarto a web Applet, but one that conforms with CLDC andMIDP and runs on a mobile device.Below is the canonical HelloWorld example which gives aquick overview of a minimal MIDP application.import javax.microedition.midlet.MIDlet;importjavax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.TextBox;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;/*** Hello, World example*/9public class HelloWorld extends MIDletimplements CommandListener {/*** Exit command*/private Command iExitCommand;/*** MIDlet constructor*/public HelloWorld() {iExitCommand = new Command("EXIT",Command.EXIT, 1);}/*** Signals the MIDlet that it has enteredthe Active state.*/public void startApp() {TextBox textBox =new TextBox("Hello World", "Hello,World!", 256, 0);textBox.addCommand(iExitCommand);textBox.setCommandListener(this);Display.getDisplay(this)10.setCurrent(textBox);}/*** Signals the MIDlet to enter the Pausedstate.*/public void pauseApp() {}/*** Signals the MIDlet to terminate and enterthe Destroyed state.*/public void destroyApp(boolean aUnconditional) {}/*** Indicates that a command event hasoccurred on a Displayable.*/public void commandAction(Command aCommand,Displayable aScreen) {if (aCommand == iExitCommand) {notifyDestroyed();}}}11Now we will explain each section in more detail.importThe first six lines import MIDP-specific classes requiredfor the HelloWorld example, which are a part of MIDPalong with a modified subset of the Java programminglanguage:• The javax.microedition.midlet.MIDlet class• The javax.microedition.lcdui.CommandListenerinterface• User interface (UI) classes.(There is also always an implicit import to the java.lang.*package).public class HelloWorld extends MIDletThis line declares that our HelloWorld is extending theonly class in the javax.microedition.midlet.* package, theMIDlet class.Each MIDP application must provide a derived instand ofthe abstract MIDlet class, which overrides the followingthree MIDlet lifecycle methods:• MIDlet.startApp()• MIDlet.pauseApp()• MIDlet.destroyApp()The MIDlet life cycle is well defined in the MIDPspecification below.121.

The Application Management Software (AMS) createsa new instance of a MIDlet and the defaultconstructor for the MIDlet is called.2. The MIDlet is now in the Paused state.3. When the AMS has decided that now the MIDletshould run, it calls startApp() method so that theMIDlet can acquire any resources it needs and beginto perform its service. The MIDlet is now in the Activestate.4. When the AMS has determined that the MIDlet is nolonger needed, it signals the MIDlet to stopperforming its service and to release any resources itcurrently holds by calling the destroyApp().The MIDlet is now in the Destroyed state.5. During MIDlet execution the AMS might want theMIDlet to significantly reduce the amount ofresources it is consuming (this could happen, forexample, when a phone call comes in).

The AMS willthen signal to the MIDlet to reduce its resourceconsumption by calling the pauseApp() method andthe MIDlet will then move to be in the Paused state.13implements CommandListenerThis line declares that the HelloWorld MIDlet implementsthe CommandListener interface that is used byapplications which need to receive high-level events fromthe implementation.The CommandListener interface has a single method:public void commandAction(Command c, Displayable d)which is invoked by the implementation to indicate that acommand event has occurred on Displayable d.At the bottom of the HelloWorld you will see how theMIDlet implements this callback method.private Command iExitCommand;In this line, the MIDlet declares it has a member variableiExitCommand which is a reference to an instance ofjavax.microedition.lcdui.Command.14A Command can be implemented in various user interfaceforms, which have a semantic of an activation of a singleaction.

This can be a soft button, item in a menu, andpossibly even a speech interface may present thisCommand as a voice tag.public HelloWorld() {iExitCommand = new Command("EXIT",Command.EXIT, 1);}As said before, the HelloWorld constructor will beexecuted before the startApp() method is called.A Command contains three pieces of information:• a label• a type• a priority.In our example, the constructor initializes theiExitCommand to display a label “EXIT” and to be oftype Command.EXIT. It does not mean that when the userinvokes this command, the application will exitautomatically. Only when theCommandListener.commandAction() is called, shouldthe MIDlet decide if it wants to exit.public void startApp()15As explained about MIDlet life cycle, when the AMSdecides that HelloWorld should run, it calls startApp()method.In this method HelloWorld will acquire any resources itneeds and will then move into the Active state.TextBox textBox = new TextBox("Hello World","Hello, World!", 256, 0);This line shows the initialization of the TextBox screen.All objects that have the capability of being placed on thedisplay derive from a base class called Displayable.MIDP lcdui defines two hierarchies of Displayables:• Higher-level - Screen is the common super class of allhigh-level user interface classes.

The contentsdisplayed and their interaction with the user isdefined by concrete subclasses.• Lower-level - Although not in this example, thesecond hierarchy derives from the Canvas base classfor handling low-level graphical operations.The TextBox in our example is one of the high-levelconcrete subclasses of Screen, which allows the user toenter and edit text.It is created with “HelloWorld” as the title string, “Hello,World!” as the initial contents, 256 characters maximumsize and no user input constraints.16“textBox.addCommand(iExitCommand);”The above line adds the iExitCommand to the display ofthe TextBox.As explained about user interface forms, theimplementation may choose to add the Command to anyof the soft buttons or add it to a menu, depending onthe phone UI platform.“textBox.setCommandListener(this);”The application provides the TextBox with the instanceof HelloWorld as the CommandListener, to receive highlevel events from the implementation.Any high-level events occurring when this TextBox isdisplayed will be notified to HelloWorld.“Display.getDisplay(this).setCurrent(textBox);”Now that the TextBox has been created, it can bedisplayed on the device screen.

In this line, the currentdisplay is set to be the newly created TextBox.When HelloWorld is first started, there is no currentDisplayable yet.A MIDlet can get a reference to a manager of the display(abstracted as the Display) and input devices of thesystem, by calling the Display.getDisplay() method.This line ensures that the display manager makesTextBox visible and enables it to interact with the user.17“public void commandAction(Command aCommand,Displayable aScreen)”This method is the implementation of theCommandListener interface which the MIDlet declaredhimself as implementing.When the implementation indicates that theiExitCommand command event has occurred, thismethod will be called.“notifyDestroyed();”The MIDlet notifies the AMS that it has entered into theDestroyed state.Please note that in a more complex example a MIDletmust perform the same cleanup and releasing ofresources it would have done if the MIDlet.destroyApp()had been called by the AMS.Hopefully, this explanation has succeeded in giving aclear example of a minimal MIDP application that displaysinformation and can receive input from the user.In the next section, we explain how to develop a MIDPapplication for Symbian OS by using industry-standardtools.18Build and run MIDP HelloWorldapplicationDownload and install the S60 Platform SDKs for SymbianOS for MIDP.Download and install the UIQ3.0 SDK for Symbian OS.Select ‘Tools’ -> ‘Java Platform Manager’ -> ‘Add Platform…’.You will be presented with ‘Add Java Platform’ page inwhich you can tick the "Java Micro Edition PlatformEmulator".

Hit ‘Next’ and select ‘Find More Java MEPlatform Folders…’. Browse to either or both the S60 3rdEdition SDK installation and/or UIQ3.0 SDK installationfolder and finish the SDK integration with NetBeans.Once the IDE and SDK installation process hascompleted, your system should be ready for developingyour first Symbian OS MIDP application!Launch NetBeans from the Start menu. Select ‘File’ -> ‘NewProject’. A Project Wizard page will be displayed. In the‘Categories’ panel, select ‘Mobile’ and in the ‘Projects’panel, select ‘Mobile Application’, then hit ‘Next’.You will be presented with ‘Name and Location’ page inwhich you can tick the ‘Create Hello MIDlet’, which willauto-generate a similar HelloWorld MIDP application.19Hit ‘Next’ and move to the ‘Default Platform Selection’page.

As you already integrated the SDK, you can nowselect either ‘S60 3rd Ed. SDK for MIDP’ in the ‘EmulatorPlatform’ list and ‘S60Emulator’ as your ‘Device’, or ‘UIQ3 SDK’ and ‘win32’.Now click ‘Finish’. The IDE will create a basic ‘Hello World’project for you. This should appear in the ‘Projects’ viewof the IDE. If you expand the project folder, you will beable to see the contents. Click on the ‘Source’ tab andthe source file will be displayed in the main editor viewof the IDE.Build the project using the ‘Build Main Project’ optionfrom the ‘Build’ menu. Assuming there are no errors(which should be the case as this project has been20generated from a template), you are now ready to run theproject in the emulator.To run the application, go to the ‘Run’ menu and selectthe ‘Run Main Project’ option.This launches the emulator progress dialog.Wait for the emulator to come up and see yourapplication running - you have now developed your firstapplication!21To close the application, do not close the emulator butclick on ‘Abort’ on the emulator progress dialog.

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

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

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

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