Windows phone 8.1 Accelerometer and updating UI

2.7k views Asked by At

I having problems finding documentation or examples regarding the proper way to use the Accelerometer as well as updating a textbox using Dispatcher. Seems like it should be easy, but all the examples are 8.0 which apparently used using Microsoft.Devices.Sensors;

Apparently you are supposed to use using Windows.Devices.Sensors; which you would think are the same, but things like Start() and Stop methods no longer exist. I was trying to use a Microsoft AccelerometerHelper class from Microsoft here

Also the older Dispatcher is now CoreDispatcher based on this?

Also was trying to use this library, but it also uses the old namespace: http://code.msdn.microsoft.com/wpapps/Shake-Gesture-Library-04c82d5f

Can anyone either provide an example or direct me to some information on how in 8.1, you would register the Accelerometer events and update the UI textbox with something like the x-axis?

Thank you very much!

3

There are 3 answers

0
gcoleman0828 On BEST ANSWER

I ended up using Silverlight 8.1 for this particular app per Microsoft. They are "looking" into why the phone API is the only one without a shake event.

4
Ku6opr On

Try this code for Windows Phone 8.1 Silverlight application. It uses Accelerometer class from Microsoft.Devices.Sensors

// initialize
Accelerometer accelerometer = new Accelerometer();
accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged;
accelerometer.Start();

void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
    Dispatcher.BeginInvoke(() =>
    {
        XAxisText.Text = e.SensorReading.Acceleration.X.ToString();
    });
}

For Windows Phone Universal application use next code:

Accelerometer accelerometer = Accelerometer.GetDefault();
accelerometer.ReadingChanged += accelerometer_ReadingChanged; 

async void accelerometer_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        XAxisText.Text = args.Reading.AccelerationX.ToString();
    });            
}
1
Traveler On

I've got the same problem and could't figure out how to make Shake event work. Then I found this examples on Microsoft site http://code.msdn.microsoft.com/Windows-Phone-81-samples-08631ca7 In the Accelerometer solution I found very nice description "Windows Phone does not have an accelerometer shake event@. So it seems like we're have to write our own implementation of Shake Event)