美文网首页
iOS App 后台保活

iOS App 后台保活

作者: 普通如我 | 来源:发表于2022-10-16 21:22 被阅读0次

#import <AVFoundation/AVFoundation.h>

// --- 后台保活

@property(nonatomic, strong) AVAudioPlayer *backgroundPlayer;/**<播放器-后台音频*/

@property(nonatomic, assign) UIBackgroundTaskIdentifier taskID;/**<后台任务ID*/

#pragma mark - Life_Cycle

- (void)dealloc {

    // 后台保活 - 删除观察者

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

#pragma mark -后台保活

- (void)keepAppLiveBackground {

    [self addNotiAddObserver];

    [self keepLiveByPlayMusic];

    [self testKeepLiveTimer];

}

- (void)keepLiveByPlayMusic {

    AVAudioSession *session = [AVAudioSession sharedInstance];

    [session setActive:YES error:nil];

    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    [self.backgroundPlayer play];

}

- (AVAudioPlayer *)backgroundPlayer {

    if(_backgroundPlayer) {

        NSURL *url = [[NSBundle mainBundle] URLForResource:@"DefaultMusicHighdown.mp3" withExtension:nil];

        _backgroundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

        [_backgroundPlayer prepareToPlay]; //异步预加载缓存

        _backgroundPlayer.numberOfLoops = -1; // 无限循环

        _backgroundPlayer.volume = 0.0; // 音量

    }

    return _backgroundPlayer;

}

- (void)addNotiAddObserver {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenAppDidBackgroundWithNoti:)

                                                name:UIApplicationDidEnterBackgroundNotification

                                              object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenWillEnterForegroundWithNoti:)

                                                name:UIApplicationWillEnterForegroundNotification

                                              object:nil];

}

- (void)whenAppDidBackgroundWithNoti:(NSNotification *)noti {

    if([noti.object isKindOfClass:[UIApplication class]]) {

        NSLog(@"通知 : App 已进入后台");

        [self.backgroundPlayer play];

        UIApplication * app = [UIApplication sharedApplication];

        __block UIBackgroundTaskIdentifier bgTask;

        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

            dispatch_async(dispatch_get_main_queue(), ^{

                if (bgTask != UIBackgroundTaskInvalid)

                {

                    bgTask = UIBackgroundTaskInvalid;

                }

            });

        }];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            dispatch_async(dispatch_get_main_queue(), ^{

                if (bgTask != UIBackgroundTaskInvalid)

                {

                    bgTask = UIBackgroundTaskInvalid;

                }

            });

        });

        self.taskID = bgTask;

    }

}

- (void)whenWillEnterForegroundWithNoti:(NSNotification *)noti {

    if([noti.object isKindOfClass:[UIApplication class]]) {

        NSLog(@"通知 : App 已进入前台");

        [self.backgroundPlayer stop];

        //

      [[UIApplication sharedApplication] endBackgroundTask:self.taskID];

        //

    }

}

- (void)testKeepLiveTimer {

    __block NSInteger count = 0;

    [NSTimer scheduledTimerWithTimeInterval:3.0 repeats:YES block:^(NSTimer * _Nonnull timer) {

        NSLog(@"count:%li", count += 3);

    }];

}

相关文章

网友评论

      本文标题:iOS App 后台保活

      本文链接:https://www.haomeiwen.com/subject/tgwdzrtx.html