Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Step counter example
package com.josiassena.simplepedometer
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), SensorEventListener {
private val sensorManager by lazy { getSystemService(Context.SENSOR_SERVICE) as SensorManager }
private var stepCounterSensor: Sensor? = null
private var hasStepCounter: Boolean = false
private var stepOffset: Float = 0f
companion object {
private const val TAG = "MainActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
hasStepCounter = packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER)
if (hasStepCounter) {
stepCounterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
}
}
override fun onStart() {
super.onStart()
sensorManager.registerListener(this, stepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL)
}
override fun onStop() {
super.onStop()
sensorManager.unregisterListener(this)
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent?) {
val values = event?.values
val overallStepsTaken = values?.get(0)
if (stepOffset == 0f) {
stepOffset = overallStepsTaken as Float
}
if (event?.sensor?.type == Sensor.TYPE_STEP_COUNTER) {
val newStepsTaken = overallStepsTaken?.minus(stepOffset)
tvStepsTaken.text = newStepsTaken?.toString()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment