I know what you’re thinking: “You are already sensitive to various orientations, how can you make my Windows Phone application the same?” Lucky you! Microsoft has written a whole API (a kind of radar, if you will) to sense Phone orientation.
Left? Right? Up? Down? Your application determines what is supported. Windows Phone supports multiple sensors providing information about the device’s orientation and location, including Compass, Gyroscope, and Accelerometer.
The Accelerometer tells your application if the user is tilting the phone and how much. Just reference Microsoft.Devices.Sensors and Microsoft.Xna.Framework.
Now, there are these few limitations to remember:
- Not while the screen is locked
- Not by a background agent
Accelerometer
The Accelerometer simply requires you to instantiate it and start it. Let’s build a sample together. I will create a Rectangle and we’ll move it around the screen according to the Accelerometer. I will do it all in code-behind. Check this out:
Get the code here.
In the code above, see the TranslateTransform? This is the easiest way to move anything – simpler than using Canvas.Top/Left, Margin, or anything else. Also, the CurrentValueChanged event tells us when the UI should be updated. We’ll handle it like this:
That’s it!
In the code above, see the Dispatcher? The event fires on a thread that is not the UI thread. The Dispatcher will return us to the UI thread. Then we adjust the TranslateTransform’s X and Y properties within the containing ContentPanel boundaries.
When the X and the Y are reported by the Accelerometer, the value a positive (left) or negative (right) double value (between –1 and 0 and 1). The values represents the degree of tilt. This is easy to add the existing TranslateTransform X or Y. A multiple (like 5) moves faster.
Combined Motion
Windows Phone includes the Combined Motion API. The Motion class handles the low-level sensor calculation and allows applications to easily obtain the device’s attitude (yaw, pitch, and roll), rotational acceleration, and linear acceleration both due to gravity and user movement.
Moment of honesty: the Combined Motion API is almost identical to the Accelerometer. Just switch “Accelerator” with “Motion” (it’s almost that easy). However, every time I try the emulator tells me the sensor is not present. Huh? So, rather than figure that out (I tried), this blog will skip right over the Combined Motion API, focusing on the Accelerometer.
Note: for what it is worth, that the Combined Motion API is the recommended API for Accelerometer data. You should prefer it for your application.
Conclusion
Accessing the Accelerometer data is easy. Adding tilt response to your application can make your program fun. Hopefully the code above will get you further along in using the Accelerometer data in your application.
Best of luck!