Issue
I am sure there is something wrong with logic but I just can't figure out what. I am trying to count for how long the user is walking by using accelerometer (phone movement) and if there is no movement for 3 seconds the time should stop and if the user starts moving again the time should start again and it should add to time achieved earlier but the time does not stop after there is no movement.
public partial class Walking : ContentPage
{
private double lastX;
private double lastHandledX;
private TimeSpan timeForRewards;
Stopwatch stopWatch = new Stopwatch();
public Walking()
{
InitializeComponent();
Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
}
private void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
{
lastX = e.Reading.Acceleration.X;
acc.Text = $"X: {e.Reading.Acceleration.X}";
}
private bool OnTimerTriggered()
{
if (lastX!=lastHandledX)
{
stopWatch.Start();
walks.Text = "Yay I am walking";
}
else
{
stopWatch.Stop();
timeForRewards += stopWatch.Elapsed;
walks.Text = $"Oh, we've stopped walking! time: {timeForRewards}";
}
lastHandledX = lastX;
return true;
}
void StartWalking_Clicked(object sender, EventArgs e)
{
if (Accelerometer.IsMonitoring)
{
Accelerometer.Stop();
}
else Accelerometer.Start(SensorSpeed.UI);
Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
Device.StartTimer(new TimeSpan(0, 0, 2), OnTimerTriggered);
}
}
}
Solution
Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
instead of Stopwatch.Start()
Starts, or resumes, measuring elapsed time for an interval.
Answered By - Sir Rufo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.