android stdio实现简单计步器的完整代码
时间: 2023-10-26 14:07:17 浏览: 46
以下是一个简单计步器的完整代码示例,可以在Android Studio中创建一个新的项目并将以下代码复制到MainActivity.java文件中:
```java
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView stepCountTextView;
private SensorManager sensorManager;
private Sensor stepSensor;
private boolean isSensorPresent;
private int stepCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stepCountTextView = findViewById(R.id.step_count_text_view);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (sensorManager != null) {
stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (stepSensor != null) {
isSensorPresent = true;
}
}
if (!isSensorPresent) {
stepCountTextView.setText("Step sensor not present!");
}
}
@Override
protected void onResume() {
super.onResume();
if (isSensorPresent) {
sensorManager.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
@Override
protected void onPause() {
super.onPause();
if (isSensorPresent) {
sensorManager.unregisterListener(this);
}
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
stepCount = (int) event.values[0];
stepCountTextView.setText("Step count: " + stepCount);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
```
此代码使用Android的传感器API来实现计步器。在onCreate方法中,它检查设备是否支持计步器传感器,如果支持,则注册SENSOR_DELAY_NORMAL监听器以接收步数更新。在onResume方法中,它注册了传感器监听器,而在onPause方法中注销了它。在onSensorChanged方法中,它更新步数并在UI上显示它。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)