21
Lecture 2 Event dr iven programming Mobile and Handheld Appli cations 1 Programming of Handheld and Mobile Devices Lecture 2: Event driven programming concepts Rob Pooley [email protected]

Lecture 2 Event driven programming Mobile and Handheld Applications1 Programming of Handheld and Mobile Devices Lecture 2: Event driven programming concepts

Embed Size (px)

Citation preview

Lecture 2 Event driven programming

Mobile and Handheld Applications 1

Programming of Handheld and Mobile Devices

Lecture 2: Event driven programming concepts

Rob Pooley

[email protected]

Lecture 2 Event driven programming

Mobile and Handheld Applications 2

What is event driven programming?

• All mobile device programming is essentially a version of event driven programming.

• Programs are built as state machines.• Events (such as mouse clicks or interrupts from comms

ports) cause event notices to be added to an event queue

• Event handlers maintain these, removing them and acting appropriately

• Handling one event may result in another being posted• This sounds difficult, but is really rather simple.

Lecture 2 Event driven programming

Mobile and Handheld Applications 3

How it works

Inspect event queues

Select event

Handle event

Lecture 2 Event driven programming

Mobile and Handheld Applications 4

More detail

• An event driven system has one or more event handling loops.

• For each loop there is one or more event queues.

• At the start of each cycle of each loop an event is removed from one of the event queues and its type decides what is done next.

Lecture 2 Event driven programming

Mobile and Handheld Applications 5

Variations on this theme

• In some systems the event is handled directly. • In others, there is a mechanism known as a callback,

which passes the event to a user defined method, to handle it.

• In the latter approach, the event loop is created behind the scenes and hidden from the programmer.

• We will look at both types of system. – Palm OS requires the programmer to write an explicit

event handling loop, based on a predefined event queue.

– J2ME, a Java system, hides the event queue and requires the programmer to write event handlers as callback methods matching a defined interface.

Lecture 2 Event driven programming

Mobile and Handheld Applications 6

Simple example

• The example is a very simple quiz with two categories of question and one question in each category.

• Initially the user is presented with a screen listing the categories – mathematics and history – in a form which will allow them to select one.

• This takes them to a new screen which asks the question and allows them to answer it.

• Their total score is updated accordingly and they return to the initial screen.

• We will also extend this example to show how we can store and retrieve information in each environment.

Lecture 2 Event driven programming

Mobile and Handheld Applications 7

Simple example - statechart

State1

State2

State4

[mathematics]

[history]

[not 42]

[42]

[1066]

[not 1066]

• Throughout this course we will be looking at two simple examples.

• The figure shows the simpler of these as a UML statechart.

• Statecharts are a very powerful and useful way of designing PDA applications.

• They show the key points reached as states and the paths between states are triggered by events.

Lecture 2 Event driven programming

Mobile and Handheld Applications 8

A general approach

• Note that each different screen to be displayed corresponds to a high level state in the UML statechart.

• When designing MID applications we can usually work out the high level logic, along with the sequence of screens to be used in this way.

Lecture 2 Event driven programming

Mobile and Handheld Applications 9

Second example

• Our second running example is also shown as a statechart in Figure opposite.

• It is also a game – this time with a more elaborate user interface, to allow us to explore drawing and other graphical facilities.

• We will also use a multi-player version to explore communication facilities in the various MID packages.

X to MoveX has moved

O has moved O to move

moveMessage

[valid ]

moveMessage

[valid]

[Win or draw]

[Win or draw]

[invalid]

[invalid]

Lecture 2 Event driven programming

Mobile and Handheld Applications 10

Programs on Palm OS

Lecture 2 Event driven programming

Mobile and Handheld Applications 11

Top level structure

PilotMain

StartQuizAppQuizAppEventLoopEndQuizApp

StartQuizApp

QuizAppEventLoop

EndQuizApp

do getEvent try in turn SysHandleEvent MenuHandleEvent AppHandleEvent FrmDispatchEventwhile not appStopEvent

FrmGotoForm(MainForm)

Lecture 2 Event driven programming

Mobile and Handheld Applications 12

Typical PilotMain

UInt32 PilotMain (UInt16 cmd, void *cmdPBP, UInt16 launchFlags)

{ UInt32 error = StartQuizApp(); if(error) return error; QuizAppEventLoop(); EndQuizApp(); return errNone; }

Lecture 2 Event driven programming

Mobile and Handheld Applications 13

Simple Start Application

static UInt16 StartQuizApp(void)

{

UInt16 error = 0;

FrmGotoForm(MainForm);

return errNone;

}

Lecture 2 Event driven programming

Mobile and Handheld Applications 14

Event loop

static void QuizAppEventLoop(void){ Err error; EventType event; do { EvtGetEvent(&event, evtWaitForever); if (! SysHandleEvent(&event)) if (! MenuHandleEvent(0, &event, &error)) if (! AppHandleEvent(&event)) FrmDispatchEvent(&event); } while (event.eType != appStopEvent);

Lecture 2 Event driven programming

Mobile and Handheld Applications 15

Event loop for Palm OS

• The key is that this function runs as a loop. It takes events one at a time from the system event queue, using EvtGetEvent.

• The loop terminates when the next event to be handled is an appStopEvent.

• Within the loop there is a nested if statement, which looks for events of different types

• There is only one thread active at a time.

• There is only one event queue per thread.

• Events are handled in a first come first served order.

• Events can be posted by application code, by user actions (button pushes, menu selections etc) or by the operating system.

Inspect event queue

Select event

Handle event

Possibly post event

Lecture 2 Event driven programming

Mobile and Handheld Applications 16

QuizAppEventLoop

• First it calls SysHandleEvent, from the System manager bundle, which takes any system events, handles them and returns true. If the event is not a system one, it returns false. It may post a new event to the queue as part of handling the current one.

• If the result of SysHandleEvent is false, the second conditional branch is tried, calling MenuHandleEvent, from the Menu manager bundle, which handles the event if it comes from a Menu action and returns true. It may also post a new event to the queue.

• These are both standard functions within the Palm OS. You do not need to write them

• If both Sys- and MenuHandleEvent cannot handle the event, AppHandleEvent is called to determine whether the event is an application specific one. It will handle the event and return true if the event is specific to this application. This is where a lot of the application’s unique functionality is linked to the forms defined in the Resource Editor. You write this one yourself. It may post a new event to the queue.

• If none of these accepts the event and handles it, we pass it to the Palm OS function FrmDispatchEvent. This assumes that any event left is a request to switch to a new form. It will invoke the appropriate event handler function for the current. This is described in more detail in the next section.

Lecture 2 Event driven programming

Mobile and Handheld Applications 17

EndQuizApp

static void EndQuizApp(void)

{

FrmCloseAllForms( );

}

Lecture 2 Event driven programming

Mobile and Handheld Applications 18

Event handlers and related functions

• An application should define and attach event handlers to any resources which require them. In this example there is an event handler for each form which is used.

• When AppHandleEvent is called it can detect events which request the loading of a new form and set the appropriate event handler for that form.

• An event handler is a function which is automatically called, by FrmDispatchEvent, when a particular form is active.

• In this way we set up some of the logic of our application. • In our application there are several types of form, each created

using the Resource Editor tool in the Developer Suite and each with its own buttons.

• We make the Id of each form distinct. It is not strictly necessary for resources of different types to have different Ids.

Lecture 2 Event driven programming

Mobile and Handheld Applications 19

Typical AppHandleEvent

static Boolean AppHandleEvent(EventPtr event){ UInt16 formId; FormPtr form; if (event->eType == frmLoadEvent) { // Load the form resource. formId = event->data.frmLoad.formID; form = FrmInitForm(formId); ErrFatalDisplayIf(!form, "Can't initialize form"); FrmSetActiveForm(form); switch (formId) { case MainForm: FrmSetEventHandler(form,

MainFormHandleEvent); break; case HistoryForm: FrmSetEventHandler(form,

HistoryFormHandleEvent); break;

case MathsForm: FrmSetEventHandler(form,

MathsFormHandleEvent); break; case WrongForm: FrmSetEventHandler(form,

WrongFormHandleEvent); break; case CorrectForm: FrmSetEventHandler(form,

CorrectFormHandleEvent); break; default: ErrFatalDisplay("Invalid Form Load Event"); break; } return true; } else return false;}

Lecture 2 Event driven programming

Mobile and Handheld Applications 20

FrmDispatchEvent - pseudocode

Boolean FrmDispatchEvent(EventType *event)

{

Boolean handled = result of calling Form's event handler;

if (handled) return true;

else return FrmHandleEvent(event);

}

• FrmDispatchEvent is written to allow the application to interpret events such as button presses if they are meaningful to this application.

• This is done by calling an event handler which is installed within the current form.

• If that fails, it passes these on to the system’s FrmHandleEvent.

Lecture 2 Event driven programming

Mobile and Handheld Applications 21

Example of an event handler

Boolean WrongFormHandleEvent(EventPtr event)

{ Boolean handled = false; FormPtr form; switch (event->eType) { case frmOpenEvent: form = FrmGetActiveForm(); FrmDrawForm(form); // here's where you'd add a call to

FrmSetFocus handled = true; break;case ctlSelectEvent: switch (event->data.ctlSelect.controlID) { case TryAgainButton: FrmGotoForm(MainForm); handled = true; break;

default: ErrFatalDisplay("Mysterious Wrong Form

Button Event"); handled = false; break; } break; case frmCloseEvent: MainFormDeinit(FrmGetActiveForm()); handled = false; break; default: } return handled;}