Java Code Examples for android.hardware.Sensor#TYPE_STEP_COUNTER

The following examples show how to use android.hardware.Sensor#TYPE_STEP_COUNTER . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StepDetector.java    From NewFastFrame with Apache License 2.0 11 votes vote down vote up
public void dealSensorEvent(SensorEvent sensorEvent) {
    if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        detectorNewStep(sensorEvent);
    } else if (sensorEvent.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
        int step = (int) sensorEvent.values[0];
        if (systemStepCount == 0) {
            systemStepCount = step;
        } else {
            int add = step - systemStepCount - tempStep;
            stepCount += add;
            tempStep = step - systemStepCount;
            callBack.countStep(stepCount);
        }
    } else if (sensorEvent.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
        if (sensorEvent.values[0] == 1.0f) {
            stepCount++;
            callBack.countStep(stepCount);
        }
    }
}
 
Example 2
Source File: HardwareStepDetectorService.java    From privacy-friendly-pedometer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
        case Sensor.TYPE_STEP_DETECTOR:
            this.onStepDetected(1);
            break;
        case Sensor.TYPE_STEP_COUNTER:
            if (this.mStepOffset < 0) {
                this.mStepOffset = event.values[0];
            }
            if (this.mStepOffset > event.values[0]) {
                // this should never happen?
                return;
            }
            // publish difference between last known step count and the current ones.
            this.onStepDetected((int) (event.values[0] - mStepOffset));
            // Set offset to current value so we know it at next event
            mStepOffset = event.values[0];
            break;
    }
}
 
Example 3
Source File: StepService.java    From LLApp with Apache License 2.0 6 votes vote down vote up
/**
 * 添加传感器监听
 * 1. TYPE_STEP_COUNTER API的解释说返回从开机被激活后统计的步数,当重启手机后该数据归零,
 * 该传感器是一个硬件传感器所以它是低功耗的。
 * 为了能持续的计步,请不要反注册事件,就算手机处于休眠状态它依然会计步。
 * 当激活的时候依然会上报步数。该sensor适合在长时间的计步需求。
 * <p>
 * 2.TYPE_STEP_DETECTOR翻译过来就是走路检测,
 * API文档也确实是这样说的,该sensor只用来监监测走步,每次返回数字1.0。
 * 如果需要长事件的计步请使用TYPE_STEP_COUNTER。
 */
private void addCountStepListener() {
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    Sensor detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
    if (countSensor != null) {
        stepSensorType = Sensor.TYPE_STEP_COUNTER;
        Log.v(TAG, "Sensor.TYPE_STEP_COUNTER");
        sensorManager.registerListener(StepService.this, countSensor, SensorManager.SENSOR_DELAY_NORMAL);
    } else if (detectorSensor != null) {
        stepSensorType = Sensor.TYPE_STEP_DETECTOR;
        Log.v(TAG, "Sensor.TYPE_STEP_DETECTOR");
        sensorManager.registerListener(StepService.this, detectorSensor, SensorManager.SENSOR_DELAY_NORMAL);
    } else {
        Log.v(TAG, "Count sensor not available!");
        addBasePedometerListener();
    }
}
 
Example 4
Source File: StepSensor.java    From react-native-google-fit with MIT License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    Sensor mySensor = sensorEvent.sensor;

    Log.i(TAG, "onSensorChanged");



    if (mySensor.getType() == Sensor.TYPE_STEP_COUNTER) {
        WritableMap map = Arguments.createMap();

        long curTime = System.currentTimeMillis();
        //i++;
        if ((curTime - lastUpdate) > delay) {
            final Object o = sensorEvent.values[0];
            Log.i("History", "Data point:" + sensorEvent.values[0]);

            map.putDouble("steps", sensorEvent.values[0]);
            sendEvent(this.mReactContext, "StepSensorChangedEvent", map);

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mReactContext.getApplicationContext(), "" + o, Toast.LENGTH_SHORT).show();
                }
            });
            lastUpdate = curTime;
        }
    }
}
 
Example 5
Source File: HardwareStepCounterService.java    From privacy-friendly-pedometer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int getSensorType() {
    Log.i(LOG_TAG, "getSensorType STEP_COUNTER");
    if (AndroidVersionHelper.isHardwareStepCounterEnabled(this.getPackageManager())) {
        return Sensor.TYPE_STEP_COUNTER;
    } else {
        return 0;
    }
}
 
Example 6
Source File: StepService.java    From LLApp with Apache License 2.0 5 votes vote down vote up
/**
     * 传感器监听回调
     * 记步的关键代码
     * 1. TYPE_STEP_COUNTER API的解释说返回从开机被激活后统计的步数,当重启手机后该数据归零,
     * 该传感器是一个硬件传感器所以它是低功耗的。
     * 为了能持续的计步,请不要反注册事件,就算手机处于休眠状态它依然会计步。
     * 当激活的时候依然会上报步数。该sensor适合在长时间的计步需求。
     * <p>
     * 2.TYPE_STEP_DETECTOR翻译过来就是走路检测,
     * API文档也确实是这样说的,该sensor只用来监监测走步,每次返回数字1.0。
     * 如果需要长事件的计步请使用TYPE_STEP_COUNTER。
     *
     * @param event
     */
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (stepSensorType == Sensor.TYPE_STEP_COUNTER) {
            //获取当前传感器返回的临时步数
            int tempStep = (int) event.values[0];
            //首次如果没有获取手机系统中已有的步数则获取一次系统中APP还未开始记步的步数
            if (!hasRecord) {
                hasRecord = true;
                hasStepCount = tempStep;
            } else {
                //获取APP打开到现在的总步数=本次系统回调的总步数-APP打开之前已有的步数
                int thisStepCount = tempStep - hasStepCount;
                //本次有效步数=(APP打开后所记录的总步数-上一次APP打开后所记录的总步数)
                int thisStep = thisStepCount - previousStepCount;
                //总步数=现有的步数+本次有效步数
                CURRENT_STEP += (thisStep);
                //记录最后一次APP打开到现在的总步数
                previousStepCount = thisStepCount;
            }
//            Logger.d("tempStep" + tempStep);
        } else if (stepSensorType == Sensor.TYPE_STEP_DETECTOR) {
            if (event.values[0] == 1.0) {
                CURRENT_STEP++;
            }
        }
        updateNotification();
    }
 
Example 7
Source File: PomodoroTransitionActivity.java    From WearPomodoro with GNU General Public License v2.0 5 votes vote down vote up
@DebugLog
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
        ++stepSensorTicks;
        if (stepSensorTicks > 5) {
            sensorManager.unregisterListener(this);
            pomodoroMaster.start(nextActivityType);
            finish();
        }
    }
}
 
Example 8
Source File: SensorUtil.java    From Sensor-Disabler with MIT License 5 votes vote down vote up
public static float getMinimumValueForSensor(Sensor sensor) {
    float minimumValue;
    switch (sensor.getType()) {
        case Sensor.TYPE_HEART_RATE:
        case Sensor.TYPE_LIGHT:
        case Sensor.TYPE_PROXIMITY:
        case Sensor.TYPE_STEP_COUNTER:
        case Sensor.TYPE_PRESSURE:
            minimumValue = 0;
            break;
        default:
            minimumValue = -sensor.getMaximumRange();
    }
    return minimumValue;
}
 
Example 9
Source File: XSensorManager.java    From XPrivacy with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private boolean isRestricted(XParam param, int type) throws Throwable {
	if (type == Sensor.TYPE_ALL)
		return false;
	else if (type == Sensor.TYPE_ACCELEROMETER || type == Sensor.TYPE_LINEAR_ACCELERATION) {
		if (isRestricted(param, "acceleration"))
			return true;
	} else if (type == Sensor.TYPE_GRAVITY) {
		if (isRestricted(param, "gravity"))
			return true;
	} else if (type == Sensor.TYPE_RELATIVE_HUMIDITY) {
		if (isRestricted(param, "humidity"))
			return true;
	} else if (type == Sensor.TYPE_LIGHT) {
		if (isRestricted(param, "light"))
			return true;
	} else if (type == Sensor.TYPE_MAGNETIC_FIELD || type == Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED) {
		if (isRestricted(param, "magnetic"))
			return true;
	} else if (type == Sensor.TYPE_SIGNIFICANT_MOTION) {
		if (isRestricted(param, "motion"))
			return true;
	} else if (type == Sensor.TYPE_ORIENTATION || type == Sensor.TYPE_GYROSCOPE
			|| type == Sensor.TYPE_GYROSCOPE_UNCALIBRATED) {
		if (isRestricted(param, "orientation"))
			return true;
	} else if (type == Sensor.TYPE_PRESSURE) {
		if (isRestricted(param, "pressure"))
			return true;
	} else if (type == Sensor.TYPE_PROXIMITY) {
		if (isRestricted(param, "proximity"))
			return true;
	} else if (type == Sensor.TYPE_GAME_ROTATION_VECTOR || type == Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR
			|| type == Sensor.TYPE_ROTATION_VECTOR) {
		if (isRestricted(param, "rotation"))
			return true;
	} else if (type == Sensor.TYPE_TEMPERATURE || type == Sensor.TYPE_AMBIENT_TEMPERATURE) {
		if (isRestricted(param, "temperature"))
			return true;
	} else if (type == Sensor.TYPE_STEP_COUNTER || type == Sensor.TYPE_STEP_DETECTOR) {
		if (isRestricted(param, "step"))
			return true;
	} else if (type == Sensor.TYPE_HEART_RATE) {
		if (isRestricted(param, "heartrate"))
			return true;
	} else if (type == 22) {
		// 22 = TYPE_TILT_DETECTOR
		// Do nothing
	} else if (type == 23 || type == 24 || type == 25) {
		// 23 = TYPE_WAKE_GESTURE
		// 24 = TYPE_GLANCE_GESTURE
		// 25 = TYPE_PICK_UP_GESTURE
		// 23/24 This sensor is expected to only be used by the system ui
		// 25 Expected to be used internally for always on display
	} else
		Util.log(this, Log.WARN, "Unknown sensor type=" + type);
	return false;
}
 
Example 10
Source File: BatchStepSensorFragment.java    From sensors-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Register a {@link android.hardware.SensorEventListener} for the sensor and max batch delay.
 * The maximum batch delay specifies the maximum duration in microseconds for which subsequent
 * sensor events can be temporarily stored by the sensor before they are delivered to the
 * registered SensorEventListener. A larger delay allows the system to handle sensor events more
 * efficiently, allowing the system to switch to a lower power state while the sensor is
 * capturing events. Once the max delay is reached, all stored events are delivered to the
 * registered listener. Note that this value only specifies the maximum delay, the listener may
 * receive events quicker. A delay of 0 disables batch mode and registers the listener in
 * continuous mode.
 * The optimium batch delay depends on the application. For example, a delay of 5 seconds or
 * higher may be appropriate for an  application that does not update the UI in real time.
 *
 * @param maxdelay
 * @param sensorType
 */
private void registerEventListener(int maxdelay, int sensorType) {
    // BEGIN_INCLUDE(register)

    // Keep track of state so that the correct sensor type and batch delay can be set up when
    // the app is restored (for example on screen rotation).
    mMaxDelay = maxdelay;
    if (sensorType == Sensor.TYPE_STEP_COUNTER) {
        mState = STATE_COUNTER;
        /*
        Reset the initial step counter value, the first event received by the event listener is
        stored in mCounterSteps and used to calculate the total number of steps taken.
         */
        mCounterSteps = 0;
        Log.i(TAG, "Event listener for step counter sensor registered with a max delay of "
                + mMaxDelay);
    } else {
        mState = STATE_DETECTOR;
        Log.i(TAG, "Event listener for step detector sensor registered with a max delay of "
                + mMaxDelay);
    }

    // Get the default sensor for the sensor type from the SenorManager
    SensorManager sensorManager =
            (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
    // sensorType is either Sensor.TYPE_STEP_COUNTER or Sensor.TYPE_STEP_DETECTOR
    Sensor sensor = sensorManager.getDefaultSensor(sensorType);

    // Register the listener for this sensor in batch mode.
    // If the max delay is 0, events will be delivered in continuous mode without batching.
    final boolean batchMode = sensorManager.registerListener(
            mListener, sensor, SensorManager.SENSOR_DELAY_NORMAL, maxdelay);

    if (!batchMode) {
        // Batch mode could not be enabled, show a warning message and switch to continuous mode
        getCardStream().getCard(CARD_NOBATCHSUPPORT)
                .setDescription(getString(R.string.warning_nobatching));
        getCardStream().showCard(CARD_NOBATCHSUPPORT);
        Log.w(TAG, "Could not register sensor listener in batch mode, " +
                "falling back to continuous mode.");
    }

    if (maxdelay > 0 && batchMode) {
        // Batch mode was enabled successfully, show a description card
        getCardStream().showCard(CARD_BATCHING_DESCRIPTION);
    }

    // Show the explanation card
    getCardStream().showCard(CARD_EXPLANATION);

    // END_INCLUDE(register)

}
 
Example 11
Source File: SKAbstractNativeSensorModule.java    From SensingKit-Android with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressLint("InlinedApi")  // There is a check in STEP_DETECTOR and STEP_COUNTER
private static int getSensorType(SKSensorModuleType sensorType) throws SKException{

    switch (sensorType) {

        case ACCELEROMETER:
            return Sensor.TYPE_ACCELEROMETER;

        case GRAVITY:
            return Sensor.TYPE_GRAVITY;

        case LINEAR_ACCELERATION:
            return Sensor.TYPE_LINEAR_ACCELERATION;

        case GYROSCOPE:
            return Sensor.TYPE_GYROSCOPE;

        case ROTATION:
            return Sensor.TYPE_ROTATION_VECTOR;

        case MAGNETOMETER:
            return Sensor.TYPE_MAGNETIC_FIELD;

        case AMBIENT_TEMPERATURE:
            return Sensor.TYPE_AMBIENT_TEMPERATURE;

        case STEP_DETECTOR:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                return Sensor.TYPE_STEP_DETECTOR;
            }
            else
            {
                throw new SKException(TAG, "STEP_DETECTOR requires Android KitKat or greater.", SKExceptionErrorCode.UNKNOWN_ERROR);
            }

        case STEP_COUNTER:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                return Sensor.TYPE_STEP_COUNTER;
            }
            else
            {
                throw new SKException(TAG, "STEP_COUNTER requires Android KitKat or greater.", SKExceptionErrorCode.UNKNOWN_ERROR);
            }

        case LIGHT:
            return Sensor.TYPE_LIGHT;

        case LOCATION:
        case ACTIVITY:
        case BATTERY:
            throw new SKException(TAG, "Not a native SensorModule.", SKExceptionErrorCode.UNKNOWN_ERROR);

        default:
            throw new SKException(TAG, "Unknown SensorModule", SKExceptionErrorCode.UNKNOWN_ERROR);

    }
}
 
Example 12
Source File: SensorDetailFragment.java    From AndroidDemoProjects with Apache License 2.0 4 votes vote down vote up
private void populateTypeField( int type ) {
	if( type == 0 || mTypeRow == null || mType == null )
		return;

	String typeName;

	switch( type ) {
		case Sensor.TYPE_ACCELEROMETER: {
			typeName = "Accelerometer";
			break;
		}
		case Sensor.TYPE_AMBIENT_TEMPERATURE: {
			typeName = "Ambient Temperature";
			break;
		}
		case Sensor.TYPE_GAME_ROTATION_VECTOR: {
			typeName = "Game Rotation Vector";
			break;
		}
		case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR: {
			typeName = "Geomagnetic Rotation Vector";
			break;
		}
		case Sensor.TYPE_GRAVITY: {
			typeName = "Gravity";
			break;
		}
		case Sensor.TYPE_GYROSCOPE: {
			typeName = "Gyroscope";
			break;
		}
		case Sensor.TYPE_GYROSCOPE_UNCALIBRATED: {
			typeName = "Uncalibrated Gyroscope";
			break;
		}
		case Sensor.TYPE_LIGHT: {
			typeName = "Light";
			break;
		}
		case Sensor.TYPE_LINEAR_ACCELERATION: {
			typeName = "Linear Acceleration";
			break;
		}
		case Sensor.TYPE_MAGNETIC_FIELD: {
			typeName = "Magnetic Field";
			break;
		}
		case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED: {
			typeName = "Uncalibrated Magnetic Field";
			break;
		}
		case Sensor.TYPE_PRESSURE: {
			typeName = "Pressure";
			break;
		}
		case Sensor.TYPE_PROXIMITY: {
			typeName = "Proximity";
			break;
		}
		case Sensor.TYPE_RELATIVE_HUMIDITY: {
			typeName = "Relative Humidity";
			break;
		}
		case Sensor.TYPE_ROTATION_VECTOR: {
			typeName = "Rotation Vector";
			break;
		}
		case Sensor.TYPE_SIGNIFICANT_MOTION: {
			typeName = "Significant Motion";
			break;
		}
		case Sensor.TYPE_STEP_COUNTER: {
			typeName = "Step Counter";
			break;
		}
		case Sensor.TYPE_STEP_DETECTOR: {
			typeName = "Step Detector";
			break;
		}
		default: {
			typeName = "Other";
		}
	}
	mType.setText( typeName );
	mTypeRow.setVisibility( View.VISIBLE );
}
 
Example 13
Source File: SensorUtil.java    From Sensor-Disabler with MIT License 4 votes vote down vote up
@Nullable
public static String getHumanStringType(Sensor sensor) {
    switch (sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
            return "Accelerometer";

        case Sensor.TYPE_AMBIENT_TEMPERATURE:
            return "Ambient Temperature";

        case Sensor.TYPE_GAME_ROTATION_VECTOR:
            return "Game Rotation Vector";

        case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
            return "Geomagnetic Rotation Vector";

        case Sensor.TYPE_GRAVITY:
            return "Gravity";

        case Sensor.TYPE_GYROSCOPE:
            return "Gyroscope";

        case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
            return "Gyroscope (Uncalibrated)";

        case Sensor.TYPE_HEART_RATE:
            return "Heart Rate";

        case Sensor.TYPE_LIGHT:
            return "Light";

        case Sensor.TYPE_LINEAR_ACCELERATION:
            return "Linear Acceleration";

        case Sensor.TYPE_MAGNETIC_FIELD:
            return "Magnetic Field";

        case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
            return "Magnetic Field (Uncalibrated)";

        case Sensor.TYPE_PRESSURE:
            return "Pressure";

        case Sensor.TYPE_PROXIMITY:
            return "Proximity";

        case Sensor.TYPE_RELATIVE_HUMIDITY:
            return "Relative Humidity";

        case Sensor.TYPE_ROTATION_VECTOR:
            return "Rotation Vector";

        case Sensor.TYPE_SIGNIFICANT_MOTION:
            return "Significant Motion";

        case Sensor.TYPE_STEP_COUNTER:
            return "Step Counter";

        case Sensor.TYPE_STEP_DETECTOR:
            return "Step Detector";

        case Sensor.TYPE_ORIENTATION:
            return "Orientation";

        case Sensor.TYPE_TEMPERATURE:
            return "Temperature";
    }
    return null;
}
 
Example 14
Source File: SensorUtil.java    From Sensor-Disabler with MIT License 4 votes vote down vote up
public static String[] getLabelsForSensor(Context context, Sensor sensor) {
    String[] labels;
    switch (sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
            labels = context.getResources().getStringArray(R.array.accelerometer_values);
            break;
        case Sensor.TYPE_AMBIENT_TEMPERATURE:
            labels = context.getResources().getStringArray(R.array.ambient_temperature_values);
            break;
        case Sensor.TYPE_GAME_ROTATION_VECTOR:
            labels = context.getResources().getStringArray(R.array.game_rotation_vector_values);
            break;
        case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
            labels = context.getResources().getStringArray(R.array.rotation_vector_values);
            break;
        case Sensor.TYPE_GRAVITY:
            labels = context.getResources().getStringArray(R.array.gravity_values);
            break;
        case Sensor.TYPE_GYROSCOPE:
            labels = context.getResources().getStringArray(R.array.gyroscore_values);
            break;
        case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
            labels = context.getResources().getStringArray(R.array.gyroscore_uncalibrated_values);
            break;
        case Sensor.TYPE_HEART_RATE:
            labels = context.getResources().getStringArray(R.array.heart_rate_values);
            break;
        case Sensor.TYPE_LIGHT:
            labels = context.getResources().getStringArray(R.array.light_values);
            break;
        case Sensor.TYPE_LINEAR_ACCELERATION:
            labels = context.getResources().getStringArray(R.array.linear_acceleration_values);
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            labels = context.getResources().getStringArray(R.array.magnetic_values);
            break;
        case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
            labels = context.getResources().getStringArray(R.array.magnetic_field_uncalibrated_values);
            break;
        case Sensor.TYPE_PRESSURE:
            labels = context.getResources().getStringArray(R.array.pressure_values);
            break;
        case Sensor.TYPE_PROXIMITY:
            labels = context.getResources().getStringArray(R.array.proximity_values);
            break;
        case Sensor.TYPE_RELATIVE_HUMIDITY:
            labels = context.getResources().getStringArray(R.array.relative_humidity_values);
            break;
        case Sensor.TYPE_ROTATION_VECTOR:
            labels = context.getResources().getStringArray(R.array.rotation_vector_values);
            break;
        case Sensor.TYPE_STEP_COUNTER:
            labels = context.getResources().getStringArray(R.array.step_counter_values);
            break;
        default:
            labels = new String[]{};
    }
    return labels;
}
 
Example 15
Source File: BatchStepSensorFragment.java    From android-BatchStepSensor with Apache License 2.0 4 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    // BEGIN_INCLUDE(sensorevent)
    // store the delay of this event
    recordDelay(event);
    final String delayString = getDelayString();

    if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
        // A step detector event is received for each step.
        // This means we need to count steps ourselves

        mSteps += event.values.length;

        // Update the card with the latest step count
        getCardStream().getCard(CARD_COUNTING)
                .setTitle(getString(R.string.counting_title, mSteps))
                .setDescription(getString(R.string.counting_description,
                        getString(R.string.sensor_detector), mMaxDelay, delayString));

        Log.i(TAG,
                "New step detected by STEP_DETECTOR sensor. Total step count: " + mSteps);

    } else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {

        /*
        A step counter event contains the total number of steps since the listener
        was first registered. We need to keep track of this initial value to calculate the
        number of steps taken, as the first value a listener receives is undefined.
         */
        if (mCounterSteps < 1) {
            // initial value
            mCounterSteps = (int) event.values[0];
        }

        // Calculate steps taken based on first counter value received.
        mSteps = (int) event.values[0] - mCounterSteps;

        // Add the number of steps previously taken, otherwise the counter would start at 0.
        // This is needed to keep the counter consistent across rotation changes.
        mSteps = mSteps + mPreviousCounterSteps;

        // Update the card with the latest step count
        getCardStream().getCard(CARD_COUNTING)
                .setTitle(getString(R.string.counting_title, mSteps))
                .setDescription(getString(R.string.counting_description,
                        getString(R.string.sensor_counter), mMaxDelay, delayString));
        Log.i(TAG, "New step detected by STEP_COUNTER sensor. Total step count: " + mSteps);
        // END_INCLUDE(sensorevent)
    }
}
 
Example 16
Source File: BatchStepSensorFragment.java    From android-BatchStepSensor with Apache License 2.0 4 votes vote down vote up
/**
 * Register a {@link android.hardware.SensorEventListener} for the sensor and max batch delay.
 * The maximum batch delay specifies the maximum duration in microseconds for which subsequent
 * sensor events can be temporarily stored by the sensor before they are delivered to the
 * registered SensorEventListener. A larger delay allows the system to handle sensor events more
 * efficiently, allowing the system to switch to a lower power state while the sensor is
 * capturing events. Once the max delay is reached, all stored events are delivered to the
 * registered listener. Note that this value only specifies the maximum delay, the listener may
 * receive events quicker. A delay of 0 disables batch mode and registers the listener in
 * continuous mode.
 * The optimium batch delay depends on the application. For example, a delay of 5 seconds or
 * higher may be appropriate for an  application that does not update the UI in real time.
 *
 * @param maxdelay
 * @param sensorType
 */
private void registerEventListener(int maxdelay, int sensorType) {
    // BEGIN_INCLUDE(register)

    // Keep track of state so that the correct sensor type and batch delay can be set up when
    // the app is restored (for example on screen rotation).
    mMaxDelay = maxdelay;
    if (sensorType == Sensor.TYPE_STEP_COUNTER) {
        mState = STATE_COUNTER;
        /*
        Reset the initial step counter value, the first event received by the event listener is
        stored in mCounterSteps and used to calculate the total number of steps taken.
         */
        mCounterSteps = 0;
        Log.i(TAG, "Event listener for step counter sensor registered with a max delay of "
                + mMaxDelay);
    } else {
        mState = STATE_DETECTOR;
        Log.i(TAG, "Event listener for step detector sensor registered with a max delay of "
                + mMaxDelay);
    }

    // Get the default sensor for the sensor type from the SenorManager
    SensorManager sensorManager =
            (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
    // sensorType is either Sensor.TYPE_STEP_COUNTER or Sensor.TYPE_STEP_DETECTOR
    Sensor sensor = sensorManager.getDefaultSensor(sensorType);

    // Register the listener for this sensor in batch mode.
    // If the max delay is 0, events will be delivered in continuous mode without batching.
    final boolean batchMode = sensorManager.registerListener(
            mListener, sensor, SensorManager.SENSOR_DELAY_NORMAL, maxdelay);

    if (!batchMode) {
        // Batch mode could not be enabled, show a warning message and switch to continuous mode
        getCardStream().getCard(CARD_NOBATCHSUPPORT)
                .setDescription(getString(R.string.warning_nobatching));
        getCardStream().showCard(CARD_NOBATCHSUPPORT);
        Log.w(TAG, "Could not register sensor listener in batch mode, " +
                "falling back to continuous mode.");
    }

    if (maxdelay > 0 && batchMode) {
        // Batch mode was enabled successfully, show a description card
        getCardStream().showCard(CARD_BATCHING_DESCRIPTION);
    }

    // Show the explanation card
    getCardStream().showCard(CARD_EXPLANATION);

    // END_INCLUDE(register)

}
 
Example 17
Source File: StepCounterUpdatesProvider.java    From PrivacyStreams with Apache License 2.0 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
StepCounterUpdatesProvider(int sensorDelay) {
    super(Sensor.TYPE_STEP_COUNTER, sensorDelay);
}
 
Example 18
Source File: BatchStepSensorFragment.java    From sensors-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    // BEGIN_INCLUDE(sensorevent)
    // store the delay of this event
    recordDelay(event);
    final String delayString = getDelayString();

    if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
        // A step detector event is received for each step.
        // This means we need to count steps ourselves

        mSteps += event.values.length;

        // Update the card with the latest step count
        getCardStream().getCard(CARD_COUNTING)
                .setTitle(getString(R.string.counting_title, mSteps))
                .setDescription(getString(R.string.counting_description,
                        getString(R.string.sensor_detector), mMaxDelay, delayString));

        Log.i(TAG,
                "New step detected by STEP_DETECTOR sensor. Total step count: " + mSteps);

    } else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {

        /*
        A step counter event contains the total number of steps since the listener
        was first registered. We need to keep track of this initial value to calculate the
        number of steps taken, as the first value a listener receives is undefined.
         */
        if (mCounterSteps < 1) {
            // initial value
            mCounterSteps = (int) event.values[0];
        }

        // Calculate steps taken based on first counter value received.
        mSteps = (int) event.values[0] - mCounterSteps;

        // Add the number of steps previously taken, otherwise the counter would start at 0.
        // This is needed to keep the counter consistent across rotation changes.
        mSteps = mSteps + mPreviousCounterSteps;

        // Update the card with the latest step count
        getCardStream().getCard(CARD_COUNTING)
                .setTitle(getString(R.string.counting_title, mSteps))
                .setDescription(getString(R.string.counting_description,
                        getString(R.string.sensor_counter), mMaxDelay, delayString));
        Log.i(TAG, "New step detected by STEP_COUNTER sensor. Total step count: " + mSteps);
        // END_INCLUDE(sensorevent)
    }
}