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#.
5,350 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ken Tucker 5,851 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;
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.