Friday, April 29, 2011

PhoneGap Lifecycle Events

With the release of PhoneGap version 0.9.5 all of the major platforms (Android, BlackBerry and iOS) now support lifecycle events. Documentation for the events will be available in the Events section of docs.phonegap.com but I thought I'd put together a small post explaining it in more details.

Whenever talking about events a finite state diagram is usually the best place to start.


When you start an application the load event is fired when all of the content has finished loading.  You can register an event listener for the load event in the body tag.
<script type="text/javascript" charset="utf-8">

function onLoad() {
  // handle on load event
}
</script>

<body onload="onLoad()">

However, this is not the most important event from a PhoneGap perspective. The PhoneGap API is not ready until you receive the deviceready event.  You should register for the deviceready event in your load event handler.  Wait until you get this event before you start calling PhoneGap API commands.
<script type="text/javascript" charset="utf-8">

function onLoad() {
  document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
  // PhoneGap is ready to be used
}
</script>

<body onload="onLoad()">

Once your application is up and running you can register for a couple of other lifecycle events in pause and resume.  The pause event is called when your application leaves the foreground and is suspended by the operating system.  The application is not closed it is just in the Paused state.  When the application is returned from the background and placed into the foreground the resume event is fired and your app is back in the Running state.
<script type="text/javascript" charset="utf-8">

function onLoad() {
  document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
  // Register the event listener
  document.addEventListener("pause", onPause, false);
  document.addEventListener("resume", onResume, false);
}

function onPause() {
  console.log("I've been paused");
}

function onResume() {
  console.log("I've been resumed");
}

</script>

<body onload="onLoad()">

When you application exits the unload event is called.  This is a useful event if your application needs to save some state data. You would register your unload listener the same as you would for the load event by adding it to the body tag.
<body onload="onLoad()" onunload="onUnLoaded()">

It is worth noting that if your application is in the Running state when it told by the OS to unload it will first be paused so the pause event will fire before the unload event.

If you want the full HTML listing you can find it here.

Monday, April 11, 2011