androidandroid-sensorssamsung-galaxysensormanager

Simple stepCounter doesn't work on different phones


I made simple stepCounter based on step counter sensor. I know that not everyone phone have this kind of sensor, so I've secured my code by Toast message in onResume.Both devices showing Toast Message that the sensor has been found. App is working properly on samsung galaxy S5 but in higher model S10E it doesn't. Does anyone know what can be cause of this error?

public class StepCounterActivity extends AppCompatActivity implements SensorEventListener {

private TextView textViewStepCounter;
private SensorManager mSensorManager;
private boolean running = false;
int stepCount = 0;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_step_counter);

    textViewStepCounter = (TextView) findViewById(R.id.textViewStepCounter);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);



}

@Override
protected void onResume() {
    super.onResume();
    running = true;
    Sensor countSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if(countSensor != null){
        mSensorManager.registerListener(this,countSensor,SensorManager.SENSOR_DELAY_UI);
        Toast.makeText(this, "Sensor found", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this,"Sensor not found",Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onPause() {
    super.onPause();
    running = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if(running){
        stepCount = (int) event.values[0];
        textViewStepCounter.setText(String.valueOf(stepCount));
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

}


Solution

  • On Android 10 you need to ask for Permissions to gain Access to the Step Sensors.

    Use this in your manifest.

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

    You might wanna ask permissions:

    if(ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED){
        //ask for permission
        requestPermissions(new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, PHYISCAL_ACTIVITY);
    }
    

    See this question: Android 10 cannot register Sensor.TYPE_STEP_COUNTER