一:需求描述
app按下home鍵后退到后臺后,過段時(shí)間再次進(jìn)入前臺不讓app重啟
二:解決思路和方法
1:在后臺播放音樂,一直循環(huán)播放無聲音樂,設(shè)置后會讓app存在后臺
在AppDelegate里面設(shè)置代碼如下
- (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];
}
}
然后在工程的設(shè)置里面的Capabilities里面設(shè)置

2:在后臺開啟定位功能,在按下home鍵后開啟定位功能在后臺運(yùn)行
- (void)appWillResignActive:(NSNotification *)notification
{
[[LBDLocationManager shareManager] startLocation];
} 開啟定位
- (void)appDidBecomeActive:(NSNotification *)notification
{
[[LBDLocationManager shareManager] stopLocation];
}//關(guān)閉定位