1

我正在使用 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"/>
4

1 回答 1

0

我建议你在真实设备上测试这个应用程序。通常,模拟器不具备某些功能,如传感器或文本转语音。

如果它仍然不起作用,请确保您的物理设备具有步长传感器。

于 2020-12-12T10:14:56.640 回答