iOS:APP背景永世保活方法

源代码 2024-9-26 16:57:06 54 0 来自 中国
Signing&Capabilites开启Audio,AirPlay,and Picture in Picture模式
应用在背景时播放声音信息,可以利用此模式播放无声音频,APP进入背景播放无声音频,可以实现APP长时间保活
代码如下
编写音乐播放类
#import <Foundation/Foundation.h>
#import<AVFoundation/AVFoundation.h>
@interface BackgroundPlayer : NSObject<AVAudioPlayerDelegate>
@property(nonatomic,strong)AVAudioPlayer* player;
- (void)startPlayer;
- (void)stopPlayer;
@end
#import "BackgroundPlayer.h"
@implementation BackgroundPlayer
- (void)startPlayer
{
    if(_player&& [_playerisPlaying]) {
        return;
    }
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
    NSString* route = [[[[[AVAudioSession sharedInstance] currentRoute] outputs] objectAtIndex:0] portType];
    if ([route isEqualToString:AVAudioSessionPortHeadphones] || [route isEqualToString:AVAudioSessionPortBluetoothA2DP] || [route isEqualToString:AVAudioSessionPortBluetoothLE] || [route isEqualToString:AVAudioSessionPortBluetoothHFP]) {
        if(@available(iOS10.0, *)) {
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
                                             withOptionsAVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP)
                                                   error:nil];
        }else{
            // Fallback on earlier versions
        }
    }else{
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
                                         withOptionsAVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDefaultToSpeaker)
                                               error:nil];
    }
    [session setActive:YESerror:nil];
    NSString *filePath = [[NSBundle mainBundle] pathForResource"payment" ofType"mp3"];
    NSURL*fileURL = [[NSURLalloc]initFileURLWithPath:filePath];
    if(!fileURL) {
        NSLog(@"找不到播放文件");
    }
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    [_player prepareToPlay];
    [_player setDelegate:self];
    _player.volume=0.0;
    _player.numberOfLoops = -1;
    BOOLret = [_playerplay];
    if(!ret) {
        NSLog(@"播放失败play failed,please turn on audio background mode");
    }
}
- (void)stopPlayer
{
    if(_player) {
        [_playerstop];
        _player=nil;
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:NOerror:nil];
        NSLog(@"播放停息stop in play background success");
    }
}
@end


在AppDelegate.m中添加监听

UIApplicationWillEnterForegroundNotification(应用进入前台通知)UIApplicationDidEnterBackgroundNotification(应用进入背景通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];


@property(nonatomic,strong)BackgroundPlayer*player;
-(void)appWillEnterForeground{
if(self.player){
[self.player stopPlayBackgroundAlive];
}
}
-(void)appDidEnterBackground{
if(_player==nil){
_player=[[BackgroundPlayer alloc]init];
}
[self.player startPlayer];
}
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 18:27, Processed in 0.156062 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表