Continuous thread to monitor hardware proximity sensor
How would开发者_如何学编程 I go about implementing a thread that runs throughout the application. I have looked at services but I am pretty sure this isnt what I want. I dont want the thread constantly checking even if the application is closed. I just want a thread running in the background of the application (even if I switch between activities) to continously check to see if the user has raised the phone to his/her ear. If the user does then it will perform an action. Any examples of something like this?
You don't need a thread or service for this. See the example in the Android API documentation for the SensorManager. Also, see below for an example:
public class SensorActivity extends Activity, implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mSensor;
public SensorActivity() {
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
// TODO: implement your action here.
}
}
This is best performed as a service. bind to the service when your activity starts, and unbind to it when your activity has completed. The service should start listening when it's bound to, and stop when unbound from.
精彩评论