androidsensormanageractivity-recognition

How to get the steps from activity recognition (Combine ActivityRecognitionApi with SensorEventListener)


I am using Google ActivityRecognitionApi for Android to know when an user is walking, running or cycling. Is there a way to get the steps that the user executed while practicing each of those activities? I am doing the activity recognition on the background using an IntentService. I need to get the steps also on the background.


Solution

  • You will need to use StepCounter sensor to get these values.

    public class StepCounterService extends Service implements SensorEventListener{
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
        //Check if the stepCounter is available first.
        List<Sensor> gravSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
        for(Sensor each : gravSensors){
        //check for sensor named stepcounter in the list.
                Log.d("Sesnor_list",each.getName());
        }
        //If it's available we can retrieve the value using following code
        Sensor sensor;
    
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        return START_STICKY;
    }
     //An onSensorChanged event gets triggered every time new step count is detected.
      @Override
    public void onSensorChanged(SensorEvent event) {
    
        if(event.sensor.getType() == sensor.TYPE_STEP_COUNTER){
            Log.d("step_count = ",event.values[0]);
        }
    
    }
    }