``我正在尝试开发一个 Windows 手机应用程序,它可以每隔 10 秒左右将加速度计读数记录到持久文件存储区域。
为此,我编写了一个程序代码,它获取加速度计读数并分别显示它们(一个文本块用于 x 读数,一个用于 y 读数,一个用于 z 读数)。然后我将所有这些读数一起存储在一个文本框中,并使用 TextChanged 事件记录对文件的更改。读数存储到独立文件存储区。
不同的功能工作正常,但我面临的问题是文件只显示加速度计读取的最后一个值,或者换句话说,文本框只保存最后读取的值。
任何人都可以建议为什么会发生这种情况,我能做些什么来解决这个问题?我使用的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
using System.Windows.Threading;
using System.IO.IsolatedStorage;
using System.IO;
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
Accelerometer a;
// Constructor
public MainPage()
{
InitializeComponent();
if (!Accelerometer.IsSupported)
{
status.Text = "Sensor not supported";
start.IsEnabled = false;
stop.IsEnabled = false;
}
}
private void start_Click(object sender, RoutedEventArgs e)
{
if (a == null)
{
a = new Accelerometer();
}
try
{
status.Text = "Starting Accelerometer";
a.TimeBetweenUpdates = TimeSpan.FromMilliseconds(1000);
a.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(a_CurrentValueChanged);
a.Start();
}
catch (Exception e1)
{
status.Text = e1.Message;
}
}
private void stop_Click(object sender, RoutedEventArgs e)
{
if (a != null)
{
a.Stop();
status.Text = "Accelerometer stopped";
}
else
{
status.Text = "Accelerometer not started";
}
}
void a_CurrentValueChanged(Object sender, SensorReadingEventArgs<AccelerometerReading> sr)
{
Dispatcher.BeginInvoke(() => UpdateUI(sr.SensorReading));
}
void UpdateUI(AccelerometerReading ar)
{
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
status.Text = "Getting Accelerometer Readings";
Vector3 xyz = ar.Acceleration;
values.Text = "X: " + xyz.X.ToString("0.00") + "\t" + "Y: " + xyz.Y.ToString("0.00") + "\t" + "Z: " + xyz.Z.ToString("0.00");
newTimer.Tick += OnTimerTick;
newTimer.Start();
}
void OnTimerTick(Object sender, EventArgs args)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
isoStore.CreateDirectory("Accelerometer");
IsolatedStorageFileStream fileStream=isoStore.OpenFile("Accelerometer\\myFile.txt",FileMode.Append,FileAccess.Write);
using(StreamWriter writeFile=new StreamWriter(fileStream))
{
writeFile.WriteLine(values.Text);
writeFile.Close();
}
}
private void read_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("Accelerometer\\myFile.txt", FileMode.Open, FileAccess.Read);
fileStream.Position = 0;
using (StreamReader reader = new StreamReader(fileStream))
{
values.Text += "\n" + reader.ReadToEnd();
}
}
}