TYPE_STEP_COUNTER sensor not found in NEXUS5X 29API

608 Views Asked by At

I am doing a step counter project in an android studio with Nexus5X API29. I need to use sensors for this. I wrote the sensor codes as below, but it still gives 'Sensor not found' error. Is there any way to fix this?

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) {

}

}

In Manifest file I also implemnent permission like this:

<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" android:required="true"/>
1

There are 1 best solutions below

0
On BEST ANSWER

I suggest you test this app on a real device. Usually, emulators don't have certain functionalities like sensors or text-to-speech.

If it still doesn't work, make sure your physical device has step sensors.