First, import the system library
# Import <avfoundation/avfoundation. h>
// Listen to the headset event
[[Avaudiosessionsharedinstance] setdelegate: Self];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
[[Avaudiosessionsharedinstance] setcategory: avaudiosessioncategoryplayback error: Nil];
// Registers the audio route change listener callback function
Audiosessionaddpropertylistener (kaudiosessionproperty_audioroutechange, audioroutechangelistenercallback, self );
Write this code to the location where you want to listen
I personally recommend
-(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoption
Because it is a global solution, everything can be responded
For example
-(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions
{
Self. Window = [[[uiappswalloc] initwithframe: [[uiscreenmainscreen] bounds] autorelease];
// Log on to VC
Loginviewcontroller * loginvc = [[loginviewcontrolleralloc] init];
Uinavigationcontroller * navnv = [[uinavigationcontrolleralloc] initwithrootviewcontroller: loginvc
];
[Navnvsetnavigationbarhidden: Yes];
[Loginvc release];
// Listen to the headset event
[[Avaudiosessionsharedinstance] setdelegate: Self];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
[[Avaudiosessionsharedinstance] setcategory: avaudiosessioncategoryplayback error: Nil];
// Registers the audio route change listener callback function
Audiosessionaddpropertylistener (kaudiosessionproperty_audioroutechange, audioroutechangelistenercallback, self );
Self. Window. rootviewcontroller = navnv;
[Navnv release];
Self. Window. backgroundcolor = [uicolorwhitecolor];
[Self. windowmakekeyandvisible];
Return yes;
}
// Triggered listening event
Void audioroutechangelistenercallback (void * inuserdata, audiosessionpropertyid inpropertyid, uint32 inpropertyvaluesize, const void * inpropertyvalue
){
// Ensure that this callback was invoked for a route change
If (inpropertyid! = Kaudiosessionproperty_audioroutechange) return;
{
// Determines the reason for the route change, to ensure that it is not
// Because of a category change.
Cfdictionaryref routechangedictionary = (cfdictionaryref) inpropertyvalue;
Cfnumberref routechangereasonref = (cfnumberref) cfdictionarygetvalue (routechangedictionary, cfstr (kaudiosession_audioroutechangekey_reason ));
Sint32 routechangereason;
Cfnumbergetvalue (routechangereasonref, kcfnumbersint32type, & routechangereason );
If (routechangereason = kaudiosessionroutechangereason_olddeviceunavailable ){
// Handle headset unplugged
Dlog (@ "no headphones! ");
} Else if (routechangereason = kaudiosessionroutechangereason_newdeviceavailable ){
// Handle headset plugged in
Dlog (@ "with headphones! ");
}
}
}
OK!