Handling Sensors in Android Kotlin

Nagendra Hari Karthick
2 min readNov 14, 2018

--

Well we all know sensors are the hardware devices which make our smart phones smarter. In this tutorial we are going to see, how to implement and use the various types of sensors used in a android phone.Now a days most android powered devices have build-in sensors that measure motion,orientation and various environmental conditions.

Some use of sensors

  1. Proximity sensors- Save battery life during calls.
  2. Temperature and humidity sensor used to calculate and report the dew point.
  3. Travelers can use accelerometer and geomagnetic field sensor for compass and other travel application.

The Android platform supports three broad categories of sensors:

  1. Motion sensors-These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
  2. Environmental sensors -These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.
  3. Position sensors -These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.

Now let’s look into the implementation

List all the sensor in my Phone

To list all the sensor in your devices and find the name of the sensors

class MainActivity : AppCompatActivity() {
private lateinit var mSensorManager: SensorManager


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get an instance of the sensor service, and use that to get an instance of
// a particular sensor.
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
val deviceSensors: List<Sensor> = mSensorManager.getSensorList(Sensor.TYPE_ALL)
Log.v("Total sensors",""+deviceSensors.size)
deviceSensors.forEach{
Log.v("Sensor name",""+it)
}
}

}

To check if a particular sensor exists or not at runtime

class MainActivity : AppCompatActivity() {
private lateinit var mSensorManager: SensorManager

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
if (mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) != null) {
// Success!
Log.v("success","yes")
} else {
// Failure!
Log.v("Failure","No sensor found")
}
}
}

You can change the sensor type ,based on your requirement.

Monitoring Sensor Events

To monitor sensor events we need to implement tow callback methods exposed through SensorEventListener interface

  1. onAccuracyChanged()- Detects the accuracy of the sensors. It is represented by four status constants : SENSOR_STATUS_ACCURACY_LOW,SENSOR_STATUS_ACCURACY_MEDIUM, SENSOR_STATUS_ACCURACY_HIGH, or SENSOR_STATUS_UNRELIABLE.
  2. onSensorChanged()-Contains the information about the new sensor data, including the accuracy of the data, the sensor that generated the data, the timestamp at which the data was generated, and the new data that the sensor recorded.
class MainActivity : AppCompatActivity(), SensorEventListener {
private lateinit var mSensorManager: SensorManager
private var mSensors: Sensor? = null
override fun
onAccuracyChanged(p0: Sensor?, p1: Int) {

}

override fun onSensorChanged(p0: SensorEvent?) {
// Sensor change value
val millibarsOfPressure = p0!!.values[0]
if (p0.sensor.type == Sensor.TYPE_LIGHT)
Toast.makeText(this, "" + millibarsOfPressure + " lx", Toast.LENGTH_SHORT).show()
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
// Define the sensor
mSensors = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT)

}

override fun onResume() {
super.onResume()
// Register the sensor on resume of the activity
mSensorManager.registerListener(this, mSensors, SensorManager.SENSOR_DELAY_NORMAL)
}

override fun onPause() {
super.onPause()
// unregister the sensor onPause else it will be active even if the activity is closed
mSensorManager.unregisterListener(this)
}
}

Thanks for Reading.

Reference https://developer.android.com/guide/topics/sensors/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Nagendra Hari Karthick
Nagendra Hari Karthick

No responses yet

Write a response