我的应用程序使用NSTimer,但似乎当iPhone进入待机模式时NSTimer不会触发(无论是通过按硬件按钮还是空闲计时器)。
当我再次激活iPhone时,我的应用程序仍然在前台。第三方应用程序在iPhone进入待机模式时会发生什么?
当我再次激活iPhone时,我的应用程序仍然在前台。第三方应用程序在iPhone进入待机模式时会发生什么?
虽然这里看不出来,但我相信原帖的作者通过在iPhone开发者论坛(此处提供)开启了一个线程找到了他问题的答案(我最终自己找到了这个线程,因为这里没有分享信息)。
如果其他人有同样的问题并在未来找到了这个页面,以下是“eskimo1”在苹果论坛上发表的有用回复(我稍微编辑了一下,以使其更易阅读而无需提供整个原始线程的上下文):
我的第一个建议是不要禁用空闲计时器,那只是一种hack。如果你想在UI事件期间保持计时器活动,请在当前运行循环上使用NSCommonModes运行计时器:
// create timer and add it to the current run loop using common modes
self.timer = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
我在构建一个小样本时使用了这篇文章中的信息。这是我在启动播放以防止音频停止时使用的代码:
AudioSession.Category = AudioSessionCategory.MediaPlayback;
当应用程序完成播放后,要将其重置为原始值:
AudioSession.Category = AudioSessionCategory.SoloAmbientSound;
完整的示例在这里:
http://github.com/migueldeicaza/monotouch-samples/tree/master/StreamingAudio/
AppDelegate
中,我实现了以下方法,并且它们的存在允许应用程序在屏幕锁定时继续运行:// this receives the notification when the device is locked
- (void)applicationWillResignActive:(UIApplication *)application
{
}
// this receives the notification that the application is about to become active again
- (void)applicationWillBecomeActive:(NSNotification *)aNotification
{
}
applicationWillBecomeActive
)。viewcontroller
类作为一个AVAudioPlayerDelegate
,并使用苹果公司“AddMusic”示例中的代码,使应用程序播放的音频警报与iPod音频等混合得很好。我只需要将这段代码放入一个在viewDidLoad期间调用的方法中即可。如果您对此感兴趣,则可以归入“应阅读本文档的人员类别”:音频会话编程指南
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// The AmbientSound category allows application audio to mix with Media Player
// audio. The category also indicates that application audio should stop playing
// if the Ring/Siilent switch is set to "silent" or the screen locks.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
我相信你的应用程序在挂起时应该正常运行。(比如Pandora Radio)
检查一下你的计时器是否因为视图被隐藏或其他事件发生而被释放。