Search code examples
androidmultithreadingsensorsbackground-process

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?


Solution

  • 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.
         }
     }