我正在用nexus5xapi29在android工作室做一个step counter项目。我需要用传感器来做这个。我写的传感器代码如下,但它仍然给'传感器未找到'错误。有什么办法解决这个问题吗?
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) {
}
}
在manifest文件中,我还嵌入如下权限:
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" android:required="true"/>
1条答案
按热度按时间9njqaruj1#
我建议你在真正的设备上测试这个应用程序。通常,仿真器没有传感器或文本到语音等特定功能。
如果仍然无法工作,请确保您的物理设备具有阶跃传感器。