最近公司在做一個(gè)關(guān)于外接藍(lán)牙音箱的功能,上網(wǎng)搜索了相關(guān)資料,發(fā)現(xiàn)大都雷同,今天做個(gè)稍許總結(jié):
1.利用遠(yuǎn)程控制事件- (void)remoteControlReceivedWithEvent:(UIEvent *)event方法
這個(gè)方法系統(tǒng)會(huì)自動(dòng)調(diào)用,可以放在AppDelegate.m文件里,也可以放在相關(guān)控制器里,前提是需要設(shè)置
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents],接收遠(yuǎn)程事件,
接收完畢后結(jié)束接收[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
接收到遠(yuǎn)程事件如播放,停止,會(huì)調(diào)用remoteControlReceivedWithEvent:方法,利用改方法里的event參數(shù)判斷是什么類型的事件:
-(void)remoteControlReceivedWithEvent:(UIEvent *)event
? ? if (event.type == UIEventTypeRemoteControl) {
? ? ? ? ?if (event.subtype == UIEventSubtypeRemoteControlPlay) {
? ? ? ? ? ? ? //....做一些事情.如播放
? ? ? ? ? ? ?} else if(//...){
? ? ? ? ? ? ? // ...
? ? ? ? ? ? ?}
? ? }
}
2.利用MPRemoteCommandCenter類
該類也會(huì)在系統(tǒng)接收到遠(yuǎn)程事件后被調(diào)用,前提是要添加相關(guān)事件的監(jiān)聽(tīng),并且該類是一個(gè)單例,如:
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
? ? NSLog(@"暫停事件");
? ? //暫停的相關(guān)事情
? ? return MPRemoteCommandHandlerStatusSuccess;
}];
[commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
? ? NSLog(@"播放事件");
? ? //播放相關(guān)事情
? ? return MPRemoteCommandHandlerStatusSuccess;
}];
在不用接收遠(yuǎn)程事件時(shí)要記的移除監(jiān)聽(tīng):
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[commandCenter.pauseCommand removeTarget:self];
[commandCenter.playCommand removeTarget:self];