The proximity sensor on the iPhone detects when the device is close to your face (or otherwise covered ). there aren't used times when using the sensor is of value, however, the Google Voice Search application has put this to good use as a means to trigger
Voice Recording for a search request. If you have an interest in doing something similar, read on.
Proximity sensor monitoring
It all begins by enabling proximity monitoring, this is followed by setting up a notification request to call a method when the proximity state changes:
View plaincopy to clipboardprint?
- // Enabled monitoring of the Sensor
- [[Uidevice currentdevice] setproximitymonitoringenabled: Yes];
- // Set up an observer for proximity changes
- [[Nsicationcenter center defacenter center] addobserver: Self selector: @ selector (sensorstatechange :)
- Name: @ "uideviceproximitystatedidchangenotification" Object: Nil];
// Enabled monitoring of the sensor [[uidevice currentdevice] setproximitymonitoringenabled: Yes]; // set up an observer for proximity changes [[nsicationicationcenter defacenter center] addobserver: Self selector: @ selector (sensorstatechange :) name: @ "uideviceproximitystatedidchangenotification" Object: Nil];
The method below will be called when the sensor state is updated, a message is printed to the debug Console Based on the sensor proximity.
View plaincopy to clipboardprint?
- -(Void) sensorstatechange :( nsicationicationcenter *) Notification
- {
- If ([[uidevice currentdevice] proximitystate] = Yes)
- Nslog (@ "device is close to user .");
- Else
- Nslog (@ "device is ~ Not ~ Closer to user .");
- }
-(Void) sensorstatechange :( nsnotificationcenter *) Notification {If ([uidevice currentdevice] proximitystate] = Yes) nslog (@ "device is close to user. "); else nslog (@" device is ~ Not ~ Closer to user .");}
Detecting proximity sensor
Not all IOS device have proximity sensors. The apple API documentation states that you shoshould enable proximity monitoring and check the proximitystate, if the return value is no, then the device does not have a sensor.
I was unable to successfully use this approach to determine if a device has a sensor. Any additional ideas or suggestions are welcome.