how to check if device is moved during last 1 minute using accelerometer xamarin

jokertn 61 Reputation points
2021-05-01T16:32:45.797+00:00

Hi there ,
am looking for method to detect if device not moved, while last 1 minute using accelerometer xamarin

        public double oldx,newx;

        protected override void OnAppearing()
        {

            base.OnAppearing();

             if (Accelerometer.IsMonitoring)
                Accelerometer.Stop();
            else
                Accelerometer.Start(SensorSpeed.UI);

            Accelerometer.ReadingChanged += Accelerometre_ReadingChanged;
            void Accelerometre_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
            {
                oldx = e.Reading.Acceleration.X;
            }

            Device.StartTimer(new TimeSpan(0, 1, 0), () =>
            {

                Accelerometer.ReadingChanged += Accelerometre_ReadingChanged1;
                void Accelerometre_ReadingChanged1(object sender, AccelerometerChangedEventArgs ee)
                {
                    newx = ee.Reading.Acceleration.X;
                }

          if(oldx != newx){
         // do somth......
//the problem here always oldx==newx           
}
        });
        }

the problem is when i compare oldx and newx always the same value , but i want to check if the mobile device cordiante change after 1 minute any solutions pls , thanks in advance.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
4,811 questions
No comments
{count} votes

Accepted answer
  1. Ken Tucker 5,801 Reputation points
    2021-05-01T18:28:15.623+00:00

    Looking at your code.

             Device.StartTimer(new TimeSpan(0, 1, 0), () =>
             {
    
                 Accelerometer.ReadingChanged += Accelerometre_ReadingChanged1;
    

    You are adding a second event handler to ReadingChanged so both Accelerometre_ReadingChanged1 and Accelerometre_ReadingChanged will get same data causing oldx and newx will be the same. You could try removing the old eventhandler before adding the new one in the timer.

             Device.StartTimer(new TimeSpan(0, 1, 0), () =>
             {
                 Accelerometer.ReadingChanged -= Accelerometre_ReadingChanged;
    
                 Accelerometer.ReadingChanged += Accelerometre_ReadingChanged1;
    
    No comments

0 additional answers

Sort by: Most helpful