ios - Detect plugIn or unplug of headphone jack from iPhone when my app is in background mode -
i want notify user when headphone jack pluggedin or unplugged iphone/ipod/ipad when app in background mode. here have code detects in foreground mode.
- (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. audiosessionaddpropertylistener(kaudiosessionproperty_audioroutechange, audiosessionpropertylistener, nil); } bool isheadsetpluggedin() { uint32 routesize = sizeof (cfstringref); cfstringref route; osstatus error = audiosessiongetproperty (kaudiosessionproperty_audioroute, &routesize, &route ); nslog(@"%@", route); return (!error && (route != null) && ([( nsstring*)route rangeofstring:@"head"].location != nsnotfound)); } void audiosessionpropertylistener(void* inclientdata, audiosessionpropertyid inid,uint32 indatasize, const void* indata) { uint32 audiorouteoverride = kaudiosessionoverrideaudioroute_speaker; // determines reason route change, ensure not // because of category change. cfdictionaryref routechangedictionary = indata; cfnumberref routechangereasonref = cfdictionarygetvalue (routechangedictionary,cfstr (kaudiosession_audioroutechangekey_reason)); sint32 routechangereason; cfnumbergetvalue (routechangereasonref, kcfnumbersint32type, &routechangereason); // "old device unavailable" indicates headset unplugged, or // device removed dock connector supports audio output. // if (routechangereason != kaudiosessionroutechangereason_olddeviceunavailable) // return; if (!isheadsetpluggedin()) { audiosessionsetproperty (kaudiosessionproperty_overrideaudioroute,sizeof (audiorouteoverride),&audiorouteoverride); nslog(@"with out headphone"); } else { uint32 audiorouteoverride = kaudiosessionoverrideaudioroute_speaker; audiosessionsetproperty (kaudiosessionproperty_overrideaudioroute, sizeof(audiorouteoverride), &audiorouteoverride); nslog(@"headphone"); } }
you try apple docs:
- (void)applicationdidenterbackground:(uiapplication *)application { bgtask = [application beginbackgroundtaskwithexpirationhandler:^{ // clean unfinished task business marking // stopped or ending task outright. [application endbackgroundtask:bgtask]; bgtask = uibackgroundtaskinvalid; }]; // start long-running task , return immediately. dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ // work associated task, preferably in chunks. [application endbackgroundtask:bgtask]; bgtask = uibackgroundtaskinvalid; }); } i think apple has given data in docs here: background execution , multitasking
Comments
Post a Comment