2013-07-18 9 views
0

내 앱이 background 모드 일 때 내 헤드폰 잭이 PluggedIn 또는 UnPlugged 일 때 내 iPhone/iPod/iPad에서 사용자에게 알리고 싶습니다. 여기에 foreground 모드에서 감지하는 코드가 있습니다.내 앱이 백그라운드 모드 일 때 iPhone에서 헤드폰 잭 플러그를 뽑거나 플러그를 뽑습니다.

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a 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 the reason for the route change, to ensure that it is not 
    //  because of a category change. 
    CFDictionaryRef routeChangeDictionary = inData; 
    CFNumberRef routeChangeReasonRef = CFDictionaryGetValue (routeChangeDictionary,CFSTR (kAudioSession_AudioRouteChangeKey_Reason)); 

    SInt32 routeChangeReason; 
    CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason); 

    // "Old device unavailable" indicates that a headset was unplugged, or that the 
    // device was removed from a dock connector that 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"); 
    } 

} 

답변

0

당신은 애플의 문서에서이 시도 할 수 :

- (void)applicationDidEnterBackground:(UIApplication *)application 

{ 

    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 

     // Clean up any unfinished task business by marking where you 

     // stopped or ending the task outright. 

     [application endBackgroundTask:bgTask]; 

     bgTask = UIBackgroundTaskInvalid; 

}]; 



    // Start the long-running task and return immediately. 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 



     // Do the work associated with the task, preferably in chunks. 



     [application endBackgroundTask:bgTask]; 

     bgTask = UIBackgroundTaskInvalid; 

    }); 

} 

을 나는 애플이 주신 생각이 여기에 자신의 문서 데이터 : Background Execution and Multitasking