Seven days with Titanium – day 7 – orientation and accelerometer

Most of the devices nowadays are equipped with an accelerometer that detect the orientation of the device or the movements the user is doing with it.

Titanium exposes this functionality through its APIs so let’s take advantage of that ๐Ÿ™‚

The orientation

The device can report 7 states of the orientation and they are defined in Titanium as follows:

  • Ti.UI.UNKNOWN – the app cannot detect the position
  • Ti.UI.FACE_DOWN – like resting on a table with the screen downward
  • Ti.UI.FACE_UP – like resting on a table but with the screen upward

While we have all this constants defined there are situations where they might not be available: in iOs when the user locks the orientation the device will report that orientation no matter how the device is held. On Android many devices can detect only the PORTRAIT and LANDSCAPE_LEFT orientations.

Since version 1.7.2 of the SDK the orientation API changed and is set per window (or activity). You can do this using the property orientationModes that accepts an array with the allowed orientation for that window. See this post on Appcelerator’s blog.

win.orientationModes = [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_RIGHT];

There is also an event that triggers when the orientation changes allowing you to make the changes you might need (adapt the UI to the new orientation for example.)

Ti.Gesture.addEventListener('orientationchange',function(e) {

The alert will show a number from 1 to 7 because the constants defined above are type INT. A good practice is to compare the orientation reported by the event with the constant and not directly with the number. In case something will change in the future this will assure you that the code will keep working.

You can find more about it in the docs page for Titanium.Gesture

The accelerometer

The accelerometer is a piece of hardware that is giving you the current position of the device in a 3D coordinates (x, y and z) vector. This can allow you for example to control the movements of an element on the screen.

To get this vector all you have to do is to catch the update event of the Titanium.Accelerometer APIs. It will return the vector we were talking about.

Ti.Accelerometer.addEventListener('update', function(e) {
    lbl.text = 'x: ' + e.x + 'y:' + e.y + 'z:' + e.z;

Again, it’s a good practice to remove the event when we don’t need it anymore to save some CPU cycles ๐Ÿ™‚

Well, that’s it for Day 7. Code strong!