<p>In this post, we will create a basic step counting application using a <span style="color: #008000;"><strong>step counter sensor</strong></span>.</p> 
 
 
 
<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex"> 
<div class="wp-block-button"><a class="wp-block-button__link has-white-color has-text-color has-background" style="background-color: #032179;" href="https://github.com/arunk7839/StepsCountApp"><strong>DOWNLOAD CODE</strong></a></div> 
</div> 
<p><amp-youtube layout="responsive" width="1200" height="675" data-videoid="p1o-r-6H9ks" title="Android Step Counting Application in kotlin"><a placeholder href="https://youtu.be/p1o-r-6H9ks"><img src="https://i.ytimg.com/vi/p1o-r-6H9ks/hqdefault.jpg" layout="fill" object-fit="cover" alt="Android Step Counting Application in kotlin"></a></amp-youtube></p> 
<h4><span style="color: #000080;"><strong>Step counter sensor</strong></span></h4> 
<ul> 
<li>The step counter sensor returns the number of steps taken by the user since the last reboot while the sensor was activated.</li> 
<li>It is ideal for fitness tracking applications. 
 
</li> 
<li>The value is returned as a float and is reset to zero only on a system reboot.</li> 
<li>This sensor requires permission <span style="color: #0000ff;"><span style="color: #0000ff;"><strong>android.permission.ACTIVITY_RECOGNITION </strong></span>which </span>allows an application to recognize the physical activity.</li> 
</ul> 
<h4><span style="color: #000080;"><strong>Creating new project</strong></span></h4> 
<p>1 . Create a new project by going to <span style="color: #008000;"><strong>File ⇒ New Android Project</strong></span>, select <strong><span style="color: #008000;">Empty</span></strong> Activity, provide app name, select language to <strong><span style="color: #008000;">kotlin</span></strong> and then finally click on <strong><span style="color: #008000;">finish</span></strong>.</p> 
<h5><strong><span style="color: #000080;">Adding Permission</span></strong></h5> 
<p><span style="color: #000000;">2 . Open the <strong><span style="color: #008000;">AndroidManifest.xml</span></strong> file and add the below permission above application tag.</span></p> 
<p><strong><span style="color: #0000ff;"> AndroidManifest.xml</span></strong></p> 
<p>For app targets Android 9 (API level 28) or below,</p> 
<ul> 
<li>Add the permission to the manifest file.</li> 
</ul> 
<pre><;uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>;</pre> 
<p>For app targets Android 10 (API level 29) or higher, we must request permission from the user at runtime, and add the above permission in the application manifest file:</p> 
<h6><span style="color: #000080;"><strong>Request permission at runtime</strong></span></h6> 
<ul> 
<li>Check if the permission is granted:</li> 
</ul> 
<pre>if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.ACTIVITY_RECOGNITION)<br />!= PackageManager.PERMISSION_GRANTED) {<br /><strong><span style="color: #008000;">// Permission is not granted</span></strong><br />}</pre> 
<ul> 
<li>If permission isn&#8217;t already granted, request the permission:</li> 
</ul> 
<pre>if (Build.VERSION.SDK_INT >;= Build.VERSION_CODES.Q) {<br /> ActivityCompat.requestPermissions(<br /> this,<br /> arrayOf(Manifest.permission.ACTIVITY_RECOGNITION),<br /> ACTIVITY_RECOGNITION_REQUEST_CODE<br /> )<br />}</pre> 
<h5><strong><span style="color: #000080;">The Layout File </span></strong></h5> 
<p>3 . The below layout file contains two textviews in which tv_stepsTaken textview, shows the no of steps taken by the user.</p> 
<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p> 
<pre><;?xml version="1.0" encoding="utf-8"?>;<br /><;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> xmlns:app="http://schemas.android.com/apk/res-auto"<br /> xmlns:tools="http://schemas.android.com/tools"<br /> android:layout_width="match_parent"<br /> android:layout_height="match_parent"<br /> tools:context=".MainActivity">;<br /><br /> <;RelativeLayout<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:background="@drawable/background"<br /> android:padding="20dp"<br /> app:layout_constraintBottom_toBottomOf="parent"<br /> app:layout_constraintEnd_toEndOf="parent"<br /> app:layout_constraintHorizontal_bias="0.5"<br /> app:layout_constraintStart_toStartOf="parent"<br /> app:layout_constraintTop_toTopOf="parent">;<br /><br /> <;TextView<br /> android:id="@+id/steps"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_centerHorizontal="true"<br /> android:text="Steps"<br /> android:textColor="@color/black"<br /> android:textSize="45sp" />;<br /><br /> <;TextView<br /> android:id="@+id/tv_stepsTaken"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_below="@id/steps"<br /> android:layout_centerHorizontal="true"<br /> android:text="0"<br /> android:textColor="@color/black"<br /> android:textSize="35sp" />;<br /><br /> <;/RelativeLayout>;<br /><br /><;/androidx.constraintlayout.widget.ConstraintLayout>;</pre> 
<p>4 . Create an instance of the default<span style="color: #0000ff;"><strong> step counter sensor </strong></span>and <span style="color: #0000ff;"><strong>sensorManager</strong></span> (lets you access the device&#8217;s sensors) :</p> 
<pre><strong><span style="color: #008000;">//initializing sensorManager instance</span></strong><br />sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager<br /><br /><strong><span style="color: #008000;">//TYPE_STEP_COUNTER: A constant describing a step counter sensor</span></strong><br />val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)</pre> 
<p>5 . Now register listener with sensor manager, if the instance of the step counter sensor is not null.</p> 
<pre>if (stepSensor == null) {<br /><span style="color: #008000;"><strong> // show toast message, if there is no sensor in the device</strong></span><br /> Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()<br />} else {<br /><strong><span style="color: #008000;"> // register listener with sensorManager</span></strong><br /> sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)<br />}</pre> 
<p>6 . Implement <strong><span style="color: #008000;">SensorEventListener</span></strong> and override the below methods as shown below:</p> 
<p><strong><span style="color: #008000;">SensorEventListener: </span></strong>Used for receiving notifications from the SensorManager when there is new sensor data.</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>
 
<ul> 
<li><strong><span style="color: #0000ff;">onSensorChanged():</span></strong> Called when there is a new sensor event.</li> 
<li><strong><span style="color: #0000ff;">onAccuracyChanged()</span></strong>: Called when the accuracy of the registered sensor has changed.</li> 
</ul> 
<pre>override fun onSensorChanged(event: SensorEvent?) {<br /><br /><strong><span style="color: #008000;"> // get textview by its id</span></strong><br /> var tv_stepsTaken = findViewById<;TextView>;(R.id.tv_stepsTaken)<br /><br /> if (running) {<br /><br /><strong><span style="color: #008000;"> //get the number of steps taken by the user.</span></strong><br /> totalSteps = event!!.values[0]<br /><br /> val currentSteps = totalSteps.toInt()<br /><br /><strong><span style="color: #008000;"> // set current steps in textview</span></strong><br /> tv_stepsTaken.text = ("$currentSteps")<br /> }<br />}<br /><br />override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {<br /> println("onAccuracyChanged: Sensor: $sensor; accuracy: $accuracy")<br />}</pre> 
<h4><span style="color: #000080;"><strong>Complete MainActivity code</strong></span></h4> 
<p><strong><span style="color: #0000ff;">MainActivity.kt</span></strong></p> 
<pre>package com.c1ctech.stepscountapp<br /><br />import android.Manifest<br />import android.content.Context<br />import android.content.pm.PackageManager<br />import android.hardware.Sensor<br />import android.hardware.SensorEvent<br />import android.hardware.SensorEventListener<br />import android.hardware.SensorManager<br />import android.os.Build<br />import androidx.appcompat.app.AppCompatActivity<br />import android.os.Bundle<br />import android.widget.TextView<br />import android.widget.Toast<br />import androidx.core.app.ActivityCompat<br />import androidx.core.content.ContextCompat<br /><br />class MainActivity : AppCompatActivity(), SensorEventListener {<br /><br /> private var sensorManager: SensorManager? = null<br /><br /><strong><span style="color: #008000;"> // variable gives the running status</span></strong><br /> private var running = false<br /><br /><strong><span style="color: #008000;"> // variable counts total steps</span></strong><br /> private var totalSteps = 0f<br /><br /> val ACTIVITY_RECOGNITION_REQUEST_CODE = 100<br /><br /> override fun onCreate(savedInstanceState: Bundle?) {<br /> super.onCreate(savedInstanceState)<br /> setContentView(R.layout.activity_main)<br /><br /><span style="color: #008000;"><strong> //check if permission isn't already granted, request the permission</strong></span><br /> if (isPermissionGranted()) {<br /> requestPermission()<br /> }<br /><br /><strong><span style="color: #008000;"> //initializing sensorManager instance</span></strong><br /> sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager<br /> }<br /><br /> override fun onResume() {<br /><br /> super.onResume()<br /> running = true<br /><br /> <strong><span style="color: #008000;"> // TYPE_STEP_COUNTER: A constant describing a step counter sensor</span></strong><br /><strong><span style="color: #008000;"> // Returns the number of steps taken by the user since the last reboot while activated</span></strong><br /><strong><span style="color: #008000;"> // This sensor requires permission android.permission.ACTIVITY_RECOGNITION.</span></strong><br /> val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)<br /><br /> if (stepSensor == null) {<br /><span style="color: #008000;"><strong> // show toast message, if there is no sensor in the device</strong></span><br /> Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()<br /> } else {<br /><strong><span style="color: #008000;"> // register listener with sensorManager</span></strong><br /> sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)<br /> }<br /> }<br /><br /> override fun onPause() {<br /> super.onPause()<br /> running = false<br /><strong><span style="color: #008000;"> // unregister listener</span></strong><br /> sensorManager?.unregisterListener(this)<br /> }<br /><br /> override fun onSensorChanged(event: SensorEvent?) {<br /><br /><strong><span style="color: #008000;"> // get textview by its id</span></strong><br /> var tv_stepsTaken = findViewById<;TextView>;(R.id.tv_stepsTaken)<br /><br /> if (running) {<br /><br /><strong><span style="color: #008000;"> //get the number of steps taken by the user.</span></strong><br /> totalSteps = event!!.values[0]<br /><br /> val currentSteps = totalSteps.toInt()<br /><br /><strong><span style="color: #008000;"> // set current steps in textview</span></strong><br /> tv_stepsTaken.text = ("$currentSteps")<br /> }<br /> }<br /><br /> override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {<br /> println("onAccuracyChanged: Sensor: $sensor; accuracy: $accuracy")<br /> }<br /><br /> private fun requestPermission() {<br /> if (Build.VERSION.SDK_INT >;= Build.VERSION_CODES.Q) {<br /> ActivityCompat.requestPermissions(<br /> this,<br /> arrayOf(Manifest.permission.ACTIVITY_RECOGNITION),<br /> ACTIVITY_RECOGNITION_REQUEST_CODE<br /> )<br /> }<br /> }<br /><br /> private fun isPermissionGranted(): Boolean {<br /> return ContextCompat.checkSelfPermission(<br /> this,<br /> Manifest.permission.ACTIVITY_RECOGNITION<br /> ) != PackageManager.PERMISSION_GRANTED<br /> }<br /><br /><strong><span style="color: #008000;"> //handle requested permission result(allow or deny)</span></strong><br /> override fun onRequestPermissionsResult(<br /> requestCode: Int,<br /> permissions: Array<;out String>;,<br /> grantResults: IntArray<br /> ) {<br /> super.onRequestPermissionsResult(requestCode, permissions, grantResults)<br /> when (requestCode) {<br /> ACTIVITY_RECOGNITION_REQUEST_CODE ->; {<br /> if ((grantResults.isNotEmpty() &;&;<br /> grantResults[0] == PackageManager.PERMISSION_GRANTED)<br /> ) {<br /> <strong><span style="color: #008000;">// Permission is granted. Continue the action or workflow</span></strong><br /><strong><span style="color: #008000;"> // in your app.</span></strong><br /> }<br /> }<br /> }<br /> }<br />}</pre> 
<p>When you run the app it will look like this as shown below:</p> 
<p><img class="alignnone wp-image-2996" src="https://c1ctech.com/wp-content/uploads/2021/12/Screenshot_20211211-182110_StepsCountApp-498x1024.jpg" alt="" width="310" height="638" /> <img class="alignnone wp-image-2997" src="https://c1ctech.com/wp-content/uploads/2021/12/Screenshot_20211211-181918_StepsCountApp-498x1024.jpg" alt="" width="308" height="634" />

