Skip to content
Snippets Groups Projects
StepCounter.java 2.84 KiB
package com.notificationFramework.stimulusStrategy;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by Peter De Jonckheere on 13/02/2018.
 * <p>
 * This class is used as an extension to the SigMotionDetect class to monitor the number of
 * steps taken since the device was booted. This service runs consistently, listening to the
 * step counter sensor.
 * </p>
 */

public class StepCounter extends Service implements SensorEventListener {

    /**
     * Holds the step count value, static to allow access by the SigMotionDetect class
     */
    static float stepCount;
    /**
     * Holds the timestamp of the last sensor report, static to allow access by the SigMotionDetect
     * class
     */
    static long timestamp;

    /**
     * The method which is called when the StepCounter service is started. Sets up the listener to
     * be registered which remains constantly registered.
     *
     * @param intent  the intent used to start this service
     * @param flags   additional information about this service
     * @param startId the unique identifier for this service
     * @return the conditions under which the OS should treat this service
     * @see android.app.Service
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SensorManager mSensorManager =
                (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
        Sensor stepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        mSensorManager.registerListener(this, stepCounter, 600000000);
        return START_STICKY;
    }

    /**
     * Changes the field values when a the step counter sensor reports a change.
     *
     * @param event the sensor event which occurred
     */
    @Override
    public void onSensorChanged(SensorEvent event) {
        stepCount = event.values[0];
        timestamp = event.timestamp / 1000000000;
    }

    /**
     * Unused as accuracy is not a major factor when using previous values. Required by
     * SensorEventListener
     *
     * @param sensor as in SensorEventListener
     * @param i      as in SensorEventListener
     * @see android.hardware.SensorEventListener
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }


    /**
     * The method which reponds to a bind request for this service.
     *
     * @param intent the intent used to rqeuest binding of this service
     * @return null as no bind requests are required.
     * @see android.app.Service
     **/
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}