我的应用程序使用NSTimer,当iPhone进入待机模式时(通过按下硬件按钮或空闲计时器),NSTimer似乎不会触发。
当我再次激活iPhone时,我的应用仍处于前台。当iPhone处于待机模式时,第三方应用会发生什么?
答案 0 :(得分:46)
虽然在这里不明显,但我相信原版海报确实通过在iPhone开发者论坛中启动一个帖子(available here)找到了他的问题的答案(我最终必须找到自己,因为信息不是' t在这里分享)。
如果其他人有相同的问题,并在将来找到该页面,这里有一个有用的回复,由Apple论坛上的某个人发布了一个名为“eskimo1”的帖子(我稍微编辑了一下,以便更容易阅读拥有整个原始线程提供的上下文):
答案 1 :(得分:14)
请参阅 iPhone OS编程指南中的应用程序中断,尤其是applicationWillResignActive
和applicationDidBecomeActive
事件。 (整个指南当然值得一读。)当你忽略这些事件时,计时器似乎会持续一段时间然后停止。听起来合乎逻辑,如果继续运行,应用程序可能很容易耗尽电池。应用程序究竟发生了什么?我猜它只是没有得到任何CPU时间 - 它会冻结,只有在你重新启动机器时解冻。
答案 2 :(得分:3)
我的第一个建议是不要禁用空闲计时器,这只是一个黑客。如果要在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];
答案 3 :(得分:1)
我最近在一个我正在使用的应用程序中遇到了这个问题,该应用程序使用多个计时器并播放一些音频提示并进行了两个相对简单的更改:
在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
{
}
参考文献:UIApplicationDelegate Protocol Reference& API文档中的NSApplication Class Reference(可通过Xcode访问,只需搜索applicationWillBecomeActive
)。
将主viewcontroller
课程设为AVAudioPlayerDelegate
并使用Apple的“AddMusic”示例中的代码,使应用播放的音频警报与iPod音频等完美混合... < / p>
我刚刚将此代码放入在viewDidLoad期间调用的方法中。如果您对此感兴趣,请参阅“谁应该阅读此文档”类别:Audio Session Programming Guide
// 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];
答案 4 :(得分:1)
我使用了这篇文章中的信息来获取我正在构建的小样本。这是我在启动播放时使用的代码,以防止音频停止:
AudioSession.Category = AudioSessionCategory.MediaPlayback;
当应用程序完成播放以重置为原始值时:
AudioSession.Category = AudioSessionCategory.SoloAmbientSound;
完整的样本在这里:
http://github.com/migueldeicaza/monotouch-samples/tree/master/StreamingAudio/
答案 5 :(得分:0)
我相信你的应用程序在暂停时应该正常运行。 (想想潘多拉电台)
检查您的计时器是否因为您的视图被隐藏或发生其他事件而被取消分配。