一:需求描述
app按下home键后退到后台后,过段时间再次进入前台不让app重启
二:解决思路和方法
1:在后台播放音乐,一直循环播放无声音乐,设置后会让app存在后台
在AppDelegate里面设置代码如下
- (void)playbackgroud{
if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) {
if (!session) {
session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[session setActive:YES error:nil];
}
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"MMPSilence" ofType:@"wav"];
NSURL * URLPath = nil;
URLPath = [[NSURL alloc] initFileURLWithPath:musicPath];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:URLPath error:nil];
[_player prepareToPlay];
[_player setDelegate:self];
_player.volume = 0;
_player.numberOfLoops = -1;
[_player play];
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if (!timerBG) {
timerBG = [NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:@selector(playbackgroud)userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timerBG forMode:NSDefaultRunLoopMode];
[timerBG fire];
}
}
然后在工程的设置里面的Capabilities里面设置
2:在后台开启定位功能,在按下home键后开启定位功能在后台运行
- (void)appWillResignActive:(NSNotification *)notification
{
[[LBDLocationManager shareManager] startLocation];
} 开启定位
- (void)appDidBecomeActive:(NSNotification *)notification
{
[[LBDLocationManager shareManager] stopLocation];
}//关闭定位