我有一个定时器应用程序,我想在定时器结束后让手机振动。我目前可以播放声音,直到按下 OK 按钮,但它只会振动一次。如何重复振动直到用户按下 OK 按钮?
这是我当前的代码
SoundEffectInstance alarmSound = PlaySound(@"Alarms/"+alarmSoundString);
VibrateController vibrate = VibrateController.Default;
vibrate.Start(new TimeSpan(0,0,0,0,1000));
MessageBoxResult alarmBox = MessageBox.Show("Press OK to stop alarm", "Timer Finished", MessageBoxButton.OK);
if (alarmBox == MessageBoxResult.OK)
{
alarmSound.Stop();
vibrate.Stop();
}
更新:我已经尝试过 Joe 的响应,如果我不调用 MessageBox.Show()
它似乎会在此时停止,直到按下 OK。
最佳答案
VibrateController.Start(Timespan)
如果您传递大于 5 秒的值,将引发错误,因此您需要采取一些技巧来让它继续运行。创建一个计时器,并将其设置为重新启动振动。例如:
已编辑
愚蠢的我,我忘记了 Messagebox 和 DispatcherTimer 将在同一个线程上运行。 Messagebox 将阻止它。试试这个。
public partial class MainPage : PhoneApplicationPage
{
TimeSpan vibrateDuration = new TimeSpan(0, 0, 0, 0, 1000);
System.Threading.Timer timer;
VibrateController vibrate = VibrateController.Default;
int timerInterval = 1300;
SoundEffectInstance alarmSound = PlaySound(@"Alarms/"+alarmSoundString);
TimeSpan alramDuration; //used to make it timeout after a while
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
timer = new Timer(new TimerCallback(timer_Tick), null, 0, timerInterval);
alramDuration = TimeSpan.FromSeconds(0);
alarmSound.Play();
MessageBoxResult alarmBox = MessageBox.Show("Press OK to stop alarm", "Timer Finished", MessageBoxButton.OK);
if (alarmBox == MessageBoxResult.OK)
{
StopAll();
}
}
void timer_Tick(object sender)
{
//keep track of how long it has been running
//stop if it has gone too long
//otheriwse restart
alramDuration = alramDuration.Add(TimeSpan.FromMilliseconds(timerInterval));
if (alramDuration.TotalMinutes > 1)
StopAll();
else
vibrate.Start(vibrateDuration);
}
void StopAll()
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
vibrate.Stop();
alarmSound.Stop();
}
}
所以我使用的是 System.Threading.Timer而不是调度程序。它主要是相同的,只是明显的 API 少了一点。您必须传递延迟量,而不是调用 Start() 和 Stop()
。要启动它,请传入 0。它将每 1.3 秒持续关闭一次,直到您调用 Change()
传入 Timeout.Infinite
一些注意事项:
vibrate.Start(vibrateDuration)
仅 从 tick 事件调用。那是因为计时器会立即启动。- 根据 Mystere Man's建议,我添加了一个超时。你会想要这样的东西。
- 您可能想要重构并清理我的样本
关于c# - 振动直到消息框关闭 Windows Phone 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8607745/