如何在 Android Studio 中构建计步应用程序?
我们中的许多人在散步或跑步时都使用过手机上的计步器。它计算用户行走的总步数并将其显示在屏幕上。计步器的另一个名称是计步器。但是你有没有想过一个应用程序如何计算我们的步数?这个应用程序的工作背后的编码是什么?让我们通过制作一个来找到这些问题的答案。
我们将在本文中构建什么?
我们将构建一个显示用户走过的步骤的应用程序。我们将在 XML 文件中使用 TextView,它将在屏幕上显示步数和标题,并使用一个 ImageView 来显示文本周围的圆圈。当用户在屏幕上长时间点击时,它会重置为 0。下面给出了一个示例 GIF,以了解我们将在本文中做什么。请注意,我们将使用Kotlin语言实现该应用程序。
分步实施
第 1 步:创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Kotlin作为编程语言。
第 2 步:使用 AndroidManifest.xml 获取用户许可
导航到app/manifests/AndroidManifest.xml并在清单中编写下面给出的代码,以获得活动识别的用户权限:
第 3 步:添加可绘制资源文件
导航到app/res/drawable并右键单击 drawable 文件夹并转到New/Drawable Resource File 。
将文件命名为圆并使用默认设置,单击确定按钮。
第 4 步:使用可绘制资源文件
在这一步中,我们将代码添加到资源文件中。我们正在应用程序的主 XML 文件中的 ImageView 中进行圆形笔划以使用它。下面是我们在上一步中制作的 circle.xml 资源文件的代码。
XML
-
XML
Kotlin
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity(), SensorEventListener {
// Added SensorEventListener the MainActivity class
// Implement all the members in the class MainActivity
// after adding SensorEventListener
// we have assigned sensorManger to nullable
private var sensorManager: SensorManager? = null
// Creating a variable which will give the running status
// and initially given the boolean value as false
private var running = false
// Creating a variable which will counts total steps
// and it has been given the value of 0 float
private var totalSteps = 0f
// Creating a variable which counts previous total
// steps and it has also been given the value of 0 float
private var previousTotalSteps = 0f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadData()
resetSteps()
// Adding a context of SENSOR_SERVICE aas Sensor Manager
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
override fun onResume() {
super.onResume()
running = true
// Returns the number of steps taken by the user since the last reboot while activated
// This sensor requires permission android.permission.ACTIVITY_RECOGNITION.
// So don't forget to add the following permission in AndroidManifest.xml present in manifest folder of the app.
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (stepSensor == null) {
// This will give a toast message to the user if there is no sensor in the device
Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()
} else {
// Rate suitable for the user interface
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onSensorChanged(event: SensorEvent?) {
// Calling the TextView that we made in activity_main.xml
// by the id given to that TextView
var tv_stepsTaken = findViewById(R.id.tv_stepsTaken)
if (running) {
totalSteps = event!!.values[0]
// Current steps are calculated by taking the difference of total steps
// and previous steps
val currentSteps = totalSteps.toInt() - previousTotalSteps.toInt()
// It will show the current steps to the user
tv_stepsTaken.text = ("$currentSteps")
}
}
fun resetSteps() {
var tv_stepsTaken = findViewById(R.id.tv_stepsTaken)
tv_stepsTaken.setOnClickListener {
// This will give a toast message if the user want to reset the steps
Toast.makeText(this, "Long tap to reset steps", Toast.LENGTH_SHORT).show()
}
tv_stepsTaken.setOnLongClickListener {
previousTotalSteps = totalSteps
// When the user will click long tap on the screen,
// the steps will be reset to 0
tv_stepsTaken.text = 0.toString()
// This will save the data
saveData()
true
}
}
private fun saveData() {
// Shared Preferences will allow us to save
// and retrieve data in the form of key,value pair.
// In this function we will save data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previousTotalSteps)
editor.apply()
}
private fun loadData() {
// In this function we will retrieve data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
// Log.d is used for debugging purposes
Log.d("MainActivity", "$savedNumber")
previousTotalSteps = savedNumber
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// We do not have to write anything in this function for this app
}
}
步骤 5:使用 activity_main.xml 文件
导航到app/res/layout/activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。
XML
步骤 6:使用 MainActivity.kt 文件
转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
科特林
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity(), SensorEventListener {
// Added SensorEventListener the MainActivity class
// Implement all the members in the class MainActivity
// after adding SensorEventListener
// we have assigned sensorManger to nullable
private var sensorManager: SensorManager? = null
// Creating a variable which will give the running status
// and initially given the boolean value as false
private var running = false
// Creating a variable which will counts total steps
// and it has been given the value of 0 float
private var totalSteps = 0f
// Creating a variable which counts previous total
// steps and it has also been given the value of 0 float
private var previousTotalSteps = 0f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadData()
resetSteps()
// Adding a context of SENSOR_SERVICE aas Sensor Manager
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
override fun onResume() {
super.onResume()
running = true
// Returns the number of steps taken by the user since the last reboot while activated
// This sensor requires permission android.permission.ACTIVITY_RECOGNITION.
// So don't forget to add the following permission in AndroidManifest.xml present in manifest folder of the app.
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (stepSensor == null) {
// This will give a toast message to the user if there is no sensor in the device
Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()
} else {
// Rate suitable for the user interface
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onSensorChanged(event: SensorEvent?) {
// Calling the TextView that we made in activity_main.xml
// by the id given to that TextView
var tv_stepsTaken = findViewById(R.id.tv_stepsTaken)
if (running) {
totalSteps = event!!.values[0]
// Current steps are calculated by taking the difference of total steps
// and previous steps
val currentSteps = totalSteps.toInt() - previousTotalSteps.toInt()
// It will show the current steps to the user
tv_stepsTaken.text = ("$currentSteps")
}
}
fun resetSteps() {
var tv_stepsTaken = findViewById(R.id.tv_stepsTaken)
tv_stepsTaken.setOnClickListener {
// This will give a toast message if the user want to reset the steps
Toast.makeText(this, "Long tap to reset steps", Toast.LENGTH_SHORT).show()
}
tv_stepsTaken.setOnLongClickListener {
previousTotalSteps = totalSteps
// When the user will click long tap on the screen,
// the steps will be reset to 0
tv_stepsTaken.text = 0.toString()
// This will save the data
saveData()
true
}
}
private fun saveData() {
// Shared Preferences will allow us to save
// and retrieve data in the form of key,value pair.
// In this function we will save data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previousTotalSteps)
editor.apply()
}
private fun loadData() {
// In this function we will retrieve data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
// Log.d is used for debugging purposes
Log.d("MainActivity", "$savedNumber")
previousTotalSteps = savedNumber
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// We do not have to write anything in this function for this app
}
}
现在运行应用程序并查看以下代码的输出:
输出:
Note:
We have to allow the permission required for the app by going to app settings and then enabling it.
It will not count the steps in the emulator, you have to use a real android device to test it.