我正在使用 Nexus5X API29 在 android studio 中做一个计步器项目。我需要为此使用传感器。我编写了如下传感器代码,但它仍然给出“未找到传感器”错误。有没有什么办法解决这一问题?
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView tv_steps;
SensorManager sensorManager;
Sensor sensor;
boolean running = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
tv_steps = (TextView) findViewById ( R.id.tv_steps );
sensorManager = (SensorManager) getSystemService ( Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume ();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor ( sensor.TYPE_STEP_COUNTER );
if(countSensor!= null){
sensorManager.registerListener ( this,countSensor,SensorManager.SENSOR_DELAY_UI );
}else {
Log.d ("Main Activity","SENSOR NOT FOUND" );
}
}
@Override
protected void onPause() {
super.onPause ();
running = false;
//if you unregister the hardware will stop detecting steps
}
@Override
public void onSensorChanged(SensorEvent event) {
if (running){
tv_steps.setText ( String.valueOf ( event.values[0] ) );
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
在清单文件中,我还实现了这样的权限:
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" android:required="true"/>