Time for action – turning the torch light on and off using the proximity sensor

In this section, we will be learning how to use the proximity sensor to turn the camera flash light on and off. As discussed earlier, most proximity sensors return the absolute distance in cm, but some return only the near and far values. The near value is 0 and the far value is the maximum range of the proximity sensor. There are a lot of common use cases for proximity sensors, such as to turn off the screen while the user is on a call, or to detect if the phone is inside the pocket or outside. For our example, we will be turning the camera flashlight on whenever any object comes near the phone screen and turning it off when the object goes far from the phone screen. The proximity sensor has on-change reporting mode, the details of reporting modes are explained in Chapter 1, Sensor Fundamentals. It is fired as soon as the proximity of the object near the phone changes.

The following code shows how to use the proximity sensor to turn the camera flash light on or off.

  1. We created a ProximitySensorActivity and followed the standard steps to get values from the sensor, which are implementing the SensorEventListener interface, initiating the SensorManager and Sensor Objects, and checking the availability of the sensors. We also declared the CameraSurfaceTexture, and Paramters objects required for the camera flashlight to work. We also called the custom initCameraFlashlight() method from onCreate() to initialize the required camera objects:

            public class ProximitySensorActivity extends Activity implements 
            SensorEventListener{ 
     
              private SensorManager mSensorManager; 
              private Sensor mSensor; 
              private boolean isSensorPresent; 
              private float distanceFromPhone; 
              private Camera mCamera; 
              private SurfaceTexture mPreviewTexture; 
              private Camera.Parameters mParameters; 
              private boolean isFlashLightOn = false; 
     
              protected void onCreate(Bundle savedInstanceState) { 
                super.onCreate(savedInstanceState); 
                setContentView(R.layout.proximitysensor_layout); 
         
                mSensorManager = (SensorManager)this.getSystemService
                (Context.SENSOR_SERVICE); 
                if(mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) 
                != null) { 
                  mSensor = mSensorManager.getDefaultSensor
                  (Sensor.TYPE_PROXIMITY); 
                  isSensorPresent = true; 
                } else { 
                  isSensorPresent = false; 
                } 
     
                initCameraFlashLight(); 
            } 
    
  2. As a best practice, we registered the listener in the onResume() method and un-registered it in the onPause() method. Inside the custom initCameraFlashlight() method, we initialized the CameraSurfaceTexture, and Paramters objects required for turning on the flashlight. In the onDestroy() method of the activity, we released the Camera object and set all the initialized object references to null:

            @Override 
            protected void onResume() { 
              super.onResume(); 
              if(isSensorPresent) { 
                mSensorManager.registerListener(this, mSensor, 
                SensorManager.SENSOR_DELAY_NORMAL); 
              } 
            } 
     
            @Override 
            protected void onPause() { 
              super.onPause(); 
              if(isSensorPresent) { 
                mSensorManager.unregisterListener(this); 
              } 
            } 
     
            public void initCameraFlashLight() 
            { 
              mCamera = Camera.open(); 
              mParameters = mCamera.getParameters(); 
              mPreviewTexture = new SurfaceTexture(0); 
              try { 
                mCamera.setPreviewTexture(mPreviewTexture); 
              } catch (IOException ex) { 
                  Log.e(TAG, ex.getLocalizedMessage()); 
                  Toast.makeText(getApplicationContext(),
                  getResources().getText(R.string.error_message), 
                  Toast.LENGTH_SHORT).show(); 
              } 
            } 
     
            @Override 
            protected void onDestroy() { 
              super.onDestroy();  
              mSensorManager = null; 
              mSensor = null; 
              mCamera.release(); 
              mCamera = null; 
          } 
    
  3. After initiating SurfaceTexture, camera, and sensors, we will now write our core logic for the app. In our custom turnTorchLightOn() method, we start the flash light by setting the flash mode to FLASH_MODE_TORCH for the camera parameters and starting the camera preview. Similarly, in the custom turnTorchLightOff() method, we stop the flash light by setting the flash mode to FLASH_MODE_OFF for the camera parameters and stopping the camera preview. Now, we call these methods from the onSensorChanged() method, depending on the distance of any object from the proximity sensor. If the distance of any object from the phone's proximity sensor is less than the maximum range of the proximity sensor, then we consider the object to be near and call the custom turnTorchLighOn() method; however, if the distance is equal to or greater than the range of the proximity sensor, we consider the object is far and call the turnTorchLightOff() method. We use the isFlashLightOn Boolean variable to maintain the on/off states of the flashlight:

            public void turnTorchLightOn() 
            { 
              mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); 
              mCamera.setParameters(mParameters); 
              mCamera.startPreview(); 
              isFlashLightOn = true; 
            } 
     
            public void turnTorchLightOff() 
           { 
             mParameters.setFlashMode(mParameters.FLASH_MODE_OFF); 
             mCamera.setParameters(mParameters); 
             mCamera.stopPreview(); 
             isFlashLightOn = false; 
           } 
     
           public void onSensorChanged(SensorEvent event) { 
             distanceFromPhone = event.values[0]; 
             if(distanceFromPhone < mSensor.getMaximumRange()) { 
               if(!isFlashLightOn) { 
                   turnTorchLightOn(); 
               } 
             } else { 
               if(isFlashLightOn) { 
                   turnTorchLightOff(); 
               } 
             } 
           } 
    

What just happened?

We used the standard steps for getting values from the proximity sensor and then used these values to turn on and off the camera flashlight in the phone. If any object comes within the range of the proximity sensor, it will turn on the flashlight; when the object goes away from its range, it will turn off the flashlight. You can determine a sensor's maximum range by using the getMaximumRange() method on the proximity sensor object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset