Best practice for accessing sensors

Android devices are manufactured by different OEMs (Original Equipment Manufactures) and come with various configurations. Each OEM is free to support its own set of sensors, which again come from different vendors. This creates the problem of device fragmentation. This problem is further complicated by addition and deprecation of sensors with different Android API levels. The following are some best practices that will help you deal with this device fragmentation problem and avoid common pitfalls and mistakes:

  • Before using the sensor coordinate system, confirm the default orientation mode of the device and check for the orientation of the x and y axes.
  • Check the availability, range, minimum delay, reporting modes, and resolution of the sensor before using it.
  • Before selecting the sampling period of any sensor, check for its power consumption. Also, keep your application precision and accuracy needs in mind before deciding the sampling period. It's recommended that you select one of the constants given by the operating system.
  • Do not block or do heavy processing on the OnSensorChanged() method. Your app might miss callbacks or go into ANR (Application Not Responding) mode. The app might even crash in the worst cases if this callback is blocked.
  • Every registration of the event listener should be paired with the un-registration of the same listener. This should be done at the right time and place. (More on this, in the next chapter).
  • Avoid using deprecated sensors and any of the deprecated APIs.
  • Never write any kind of application logic based on the delay between the sensor events. Always use the timestamp from the sensor event to do your time-related calculations.
  • If some sensors are mandatory for your application to function, then use the uses-feature filter in the Manifest.xml file and change the required value to true.
  • Check your application and its sensor behavior on more than one device, as the sensor values and range may vary with different devices.
..................Content has been hidden....................

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