Chr*_*ris 5 c# silverlight timer windows-phone-7 vibration
我有一个计时器应用程序,我想在计时器完成后振动手机.我可以播放声音,直到按下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();
}
Run Code Online (Sandbox Code Playgroud)
更新:我已经尝试了Joe的响应,如果我不调用MessageBox.Show()
它可以工作它似乎在此点停止,直到按下OK.
小智 2
VibrateController.Start(Timespan)
如果您传递的值大于 5 秒,则会抛出错误,因此您需要采取一些技巧才能使其继续运行。创建一个计时器,并将其设置为重新启动振动。例如:
已编辑
愚蠢的我,我忘记了 Messagebox 和 DispatcherTimer 将在同一个线程上运行。消息框将阻止它。尝试这个。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
所以我使用System.Threading.Timer而不是 Dispatcher。它们基本上是相同的,只是明显的 API 少了一点。Start() and Stop()
您必须传递延迟金额,而不是调用。要启动它,请传入 0。它将每 1.3 秒持续一次,直到您调用Change()
传入 Timeout.Infinite 为止
有几点需要注意:
vibrate.Start(vibrateDuration)
仅从勾选事件中调用。这是因为计时器会立即启动。 归档时间: |
|
查看次数: |
1216 次 |
最近记录: |