android.hardware.SensorEventListener

Here are the examples of the java api android.hardware.SensorEventListener taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

121 Examples 7

19 Source : UpdatesPreferenceFragment.java
with GNU General Public License v3.0
from thuryn

public clreplaced UpdatesPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

    private final String[] SUMMARIES_TO_UPDATE = { Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD, Constants.KEY_PREF_LOCATION_UPDATE_PERIOD, Constants.KEY_PREF_LOCATION_GEOCODER_SOURCE };

    private final SensorEventListener sensorListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_updates);
        SensorManager senSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        Sensor senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        boolean deviceHasAccelerometer = senSensorManager.registerListener(sensorListener, senAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
        senSensorManager.unregisterListener(sensorListener);
        Preference updateWidgetUpdatePref = findPreference(Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD);
        ListPreference updateListPref = (ListPreference) updateWidgetUpdatePref;
        int accIndex = updateListPref.findIndexOfValue("0");
        if (!deviceHasAccelerometer) {
            CharSequence[] entries = updateListPref.getEntries();
            CharSequence[] newEntries = new CharSequence[entries.length - 1];
            int i = 0;
            int j = 0;
            for (CharSequence entry : entries) {
                if (i != accIndex) {
                    newEntries[j] = entries[i];
                    j++;
                }
                i++;
            }
            updateListPref.setEntries(newEntries);
            if (updateListPref.getValue() == null) {
                updateListPref.setValueIndex(updateListPref.findIndexOfValue("60") - 1);
            }
        } else if (updateListPref.getValue() == null) {
            updateListPref.setValueIndex(accIndex);
        }
        LocationsDbHelper locationsDbHelper = LocationsDbHelper.getInstance(getActivity());
        List<Location> availableLocations = locationsDbHelper.getAllRows();
        boolean oneNoautoLocationAvailable = false;
        for (Location location : availableLocations) {
            if (location.getOrderId() != 0) {
                oneNoautoLocationAvailable = true;
                break;
            }
        }
        if (!oneNoautoLocationAvailable) {
            ListPreference locationPreference = (ListPreference) findPreference("location_update_period_pref_key");
            locationPreference.setEnabled(false);
        }
        ListPreference locationAutoPreference = (ListPreference) findPreference("location_auto_update_period_pref_key");
        locationAutoPreference.setEnabled(locationsDbHelper.getLocationByOrderId(0).isEnabled());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        int verticalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, getResources().getDisplayMetrics());
        if (view != null) {
            view.setPadding(horizontalMargin, topMargin, horizontalMargin, verticalMargin);
        }
        return view;
    }

    private void entrySummary(String key) {
        ListPreference preference = (ListPreference) findPreference(key);
        if (preference == null) {
            return;
        }
        preference.setSummary(preference.getEntry());
        if (Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD.equals(key)) {
            if ("0".equals(preference.getValue())) {
                AppPreference.setNotificationEnabled(getActivity(), true);
                AppPreference.setNotificationPresence(getActivity(), "permanent");
                AppPreference.setRegularOnlyInterval(getActivity());
            } else {
                AppPreference.setNotificationEnabled(getActivity(), false);
                AppPreference.setNotificationPresence(getActivity(), "when_updated");
                NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancelAll();
            }
        }
    }

    private void updateSummary(String key, boolean changing) {
        entrySummary(key);
        switch(key) {
            case Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD:
            case Constants.KEY_PREF_LOCATION_UPDATE_PERIOD:
                if (changing) {
                    Intent intentToStartUpdate = new Intent("org.thosp.yourlocalweather.action.RESTART_ALARM_SERVICE");
                    intentToStartUpdate.setPackage("org.thosp.yourlocalweather");
                    getActivity().startService(intentToStartUpdate);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        updateSummary(key, true);
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        updateSummaries();
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    private void updateSummaries() {
        for (String key : SUMMARIES_TO_UPDATE) {
            updateSummary(key, false);
        }
    }
}

19 Source : AccelerometerReader.java
with MIT License
from SDRausty

public clreplaced AccelerometerReader {

    public volatile float x = 0;

    public volatile float y = 0;

    public volatile float z = 0;

    public AccelerometerReader(Context ctx) throws UnsupportedOperationException {
        SensorManager sensor_manager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
        Sensor accelerometer = sensor_manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensor_manager.registerListener(listener_, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
    }

    private SensorEventListener listener_ = new SensorEventListener() {

        public void onAccuracyChanged(Sensor arg0, int arg1) {
        }

        public void onSensorChanged(SensorEvent evt) {
            float[] vals = evt.values;
            if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                x = vals[0];
                y = vals[1];
                z = vals[2];
            }
        }
    };
}

19 Source : SensorsInputController.java
with MIT License
from PacktPublishing

/**
 * Created by Raul Portales on 10/03/15.
 */
public clreplaced SensorsInputController extends InputController {

    private static final double DEGREES_PER_RADIAN = 57.2957795d;

    private static final double MAX_ANGLE = 30;

    private Activity mActivity;

    private float[] mRotationMatrix = new float[16];

    private float[] mOrientation = new float[3];

    private float[] mLastMagFields = new float[3];

    private float[] mLastAccels = new float[3];

    private int mRotation;

    private SensorEventListener mMagneticChangesListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            System.arraycopy(event.values, 0, mLastMagFields, 0, 3);
        }

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

    private SensorEventListener mAccelerometerChangesListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            System.arraycopy(event.values, 0, mLastAccels, 0, 3);
        }

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

    public SensorsInputController(YreplacedActivity yreplacedActivity) {
        mActivity = yreplacedActivity;
        mRotation = yreplacedActivity.getWindowManager().getDefaultDisplay().getRotation();
    }

    private void registerListeners() {
        SensorManager sm = (SensorManager) mActivity.getSystemService(Activity.SENSOR_SERVICE);
        sm.registerListener(mAccelerometerChangesListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
        sm.registerListener(mMagneticChangesListener, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_FASTEST);
    }

    private void unregisterListeners() {
        SensorManager sm = (SensorManager) mActivity.getSystemService(Activity.SENSOR_SERVICE);
        sm.unregisterListener(mAccelerometerChangesListener);
        sm.unregisterListener(mMagneticChangesListener);
    }

    // @Override
    // public void onSensorChanged(SensorEvent event) {
    // mHorizontalFactor = getHorizontalAxis()/45d;
    // mVerticalFactor = getVerticalAxis()/45d;
    // }
    // 
    // @Override
    // public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // }
    @Override
    public void onStart() {
        registerListeners();
    }

    @Override
    public void onStop() {
        unregisterListeners();
    }

    @Override
    public void onResume() {
        registerListeners();
    }

    @Override
    public void onPause() {
        unregisterListeners();
    }

    @Override
    public void onPreUpdate() {
        mHorizontalFactor = getHorizontalAxis() / MAX_ANGLE;
        if (mHorizontalFactor > 1) {
            mHorizontalFactor = 1;
        } else if (mHorizontalFactor < -1) {
            mHorizontalFactor = -1;
        }
        mVerticalFactor = 0;
    }

    private double getHorizontalAxis() {
        if (SensorManager.getRotationMatrix(mRotationMatrix, null, mLastAccels, mLastMagFields)) {
            if (mRotation == Surface.ROTATION_0) {
                SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, mRotationMatrix);
                SensorManager.getOrientation(mRotationMatrix, mOrientation);
                return mOrientation[1] * DEGREES_PER_RADIAN;
            } else {
                SensorManager.getOrientation(mRotationMatrix, mOrientation);
                return -mOrientation[1] * DEGREES_PER_RADIAN;
            }
        } else {
            // Case for devices that DO NOT have magnetic sensors
            if (mRotation == Surface.ROTATION_0) {
                return -mLastAccels[0] * 5;
            } else {
                return -mLastAccels[1] * -5;
            }
        }
    }
}

19 Source : VirtualSensorListener.java
with GNU Lesser General Public License v3.0
from Frazew

public clreplaced VirtualSensorListener implements SensorEventListener {

    private SensorEventListener realListener = null;

    private Sensor registeredSensor = null;

    public Sensor sensorRef = null;

    public boolean isDummyGyroListener = false;

    public VirtualSensorListener(SensorEventListener realListener, Sensor registeredSensor) {
        this.realListener = realListener;
        this.registeredSensor = registeredSensor;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == this.registeredSensor.getType()) {
            event.accuracy = SensorManager.SENSOR_STATUS_ACCURACY_HIGH;
            realListener.onSensorChanged(event);
        }
    }

    public Sensor getSensor() {
        return this.registeredSensor;
    }

    public SensorEventListener getRealListener() {
        return this.realListener;
    }

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

19 Source : SensorMetricsCollector.java
with MIT License
from facebookincubator

public synchronized void register(SensorEventListener listener, Sensor sensor) {
    if (!mEnabled) {
        return;
    }
    SensorListenerData data = new SensorListenerData(listener, sensor);
    mActiveSensorData.add(data);
    SensorData currentCount = mActiveSensors.get(sensor);
    if (currentCount == null) {
        currentCount = new SensorData(SystemClock.elapsedRealtime(), 1);
        mActiveSensors.put(sensor, currentCount);
    } else {
        currentCount.activeCount++;
    }
}

19 Source : ImuPublisherNode.java
with Apache License 2.0
from eborghi10

public clreplaced ImuPublisherNode extends AbstractNodeMain {

    private static float maxFrequency = 100.f;

    private float minElapse = 1000 / maxFrequency;

    // TODO Ensure that data from accelerometer, gyroscope, and orientation sensor that is published within the same message does not vary in terms of the time they are message, otherwise drop.
    private long previousPublishTime = System.currentTimeMillis();

    private boolean isAccelerometerMessagePending;

    private boolean isGyroscopeMessagePending;

    private boolean isOrientationMessagePending;

    private String topic_name;

    private SensorEventListener accelerometerListener;

    private SensorEventListener gyroscopeListener;

    private SensorEventListener orientationListener;

    private float ax, ay, az;

    private float aRoll, aPitch, aYaw;

    private float roll, pitch, yaw;

    private String imuFrameId;

    private float prevRoll, prevPitch, prevYaw;

    private OnFrameIdChangeListener imuFrameIdChangeListener;

    public ImuPublisherNode() {
        this.topic_name = "imu_data";
        isAccelerometerMessagePending = false;
        isGyroscopeMessagePending = false;
        isOrientationMessagePending = false;
        accelerometerListener = new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                if (!(ax == sensorEvent.values[0] && ay == sensorEvent.values[1] && az == sensorEvent.values[2])) {
                    ax = sensorEvent.values[0];
                    ay = sensorEvent.values[1];
                    az = sensorEvent.values[2];
                    isAccelerometerMessagePending = true;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        };
        gyroscopeListener = new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                if (!(aRoll == -sensorEvent.values[1] && aPitch == -sensorEvent.values[2] && aYaw == sensorEvent.values[0])) {
                    aRoll = -sensorEvent.values[1];
                    aPitch = -sensorEvent.values[2];
                    aYaw = sensorEvent.values[0];
                    isGyroscopeMessagePending = true;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        };
        orientationListener = new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                if (!(roll == -sensorEvent.values[1] && pitch == -sensorEvent.values[2] && yaw == 360 - sensorEvent.values[0])) {
                    roll = -sensorEvent.values[1];
                    pitch = -sensorEvent.values[2];
                    yaw = 360 - sensorEvent.values[0];
                    isOrientationMessagePending = true;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        };
        imuFrameIdChangeListener = new OnFrameIdChangeListener() {

            @Override
            public void onFrameIdChanged(String newFrameId) {
                imuFrameId = newFrameId;
            }
        };
    }

    @Override
    public GraphName getDefaultNodeName() {
        return GraphName.of("ros_android_sensors/imu_publisher_node");
    }

    @Override
    public void onStart(final ConnectedNode connectedNode) {
        final Publisher<Imu> imuPublisher = connectedNode.newPublisher(this.topic_name, Imu._TYPE);
        connectedNode.executeCancellableLoop(new CancellableLoop() {

            int sequenceNumber = 1;

            Header header = connectedNode.getTopicMessageFactory().newFromType(Header._TYPE);

            Imu imuMessage = imuPublisher.newMessage();

            @Override
            protected void loop() throws InterruptedException {
                long currentTimeMillis = System.currentTimeMillis();
                if (isAccelerometerMessagePending && isGyroscopeMessagePending && isOrientationMessagePending) {
                    header.setStamp(connectedNode.getCurrentTime());
                    header.setFrameId(imuFrameId);
                    header.setSeq(sequenceNumber);
                    imuMessage.setHeader(header);
                    imuMessage.getLinearAcceleration().setX(ax);
                    imuMessage.getLinearAcceleration().setY(ay);
                    imuMessage.getLinearAcceleration().setZ(az);
                    float dt = (currentTimeMillis - previousPublishTime) / 1000.f;
                    float dRoll = (roll - prevRoll);
                    if (dRoll > 180)
                        dRoll = 360 - dRoll;
                    float dPitch = (pitch - prevPitch);
                    if (dPitch > 180)
                        dPitch = 360 - dPitch;
                    float dYaw = (yaw - prevYaw);
                    if (dYaw > 180)
                        dYaw = 360 - dYaw;
                    imuMessage.getAngularVelocity().setX(dRoll / dt);
                    imuMessage.getAngularVelocity().setY(dPitch / dt);
                    imuMessage.getAngularVelocity().setZ(dYaw / dt);
                    prevRoll = roll;
                    prevPitch = pitch;
                    prevYaw = yaw;
                    imuMessage.getOrientation().setW(roll);
                    imuMessage.getOrientation().setX(roll);
                    imuMessage.getOrientation().setY(pitch);
                    imuMessage.getOrientation().setZ(yaw);
                    imuPublisher.publish(imuMessage);
                    // Wait until minimum time has elapsed
                    long elapsed = currentTimeMillis - previousPublishTime;
                    long remainingTime = (long) (minElapse - elapsed);
                    if (remainingTime > 0)
                        Thread.sleep(remainingTime);
                    previousPublishTime = System.currentTimeMillis();
                    isAccelerometerMessagePending = false;
                    isGyroscopeMessagePending = false;
                    isOrientationMessagePending = false;
                    ++this.sequenceNumber;
                } else {
                    Thread.sleep(1);
                }
            }
        });
    }

    public SensorEventListener getAccelerometerListener() {
        return accelerometerListener;
    }

    public SensorEventListener getGyroscopeListener() {
        return gyroscopeListener;
    }

    public SensorEventListener getOrientationListener() {
        return orientationListener;
    }

    public OnFrameIdChangeListener getFrameIdListener() {
        return imuFrameIdChangeListener;
    }
}

19 Source : ShakeDetectorTest.java
with Apache License 2.0
from aws-amplify

/**
 * Creates a new thread that when started will send a sensor event to the given
 * SensorEventListener for each element in the given List.
 * @param sensorValues List where each element represents the acceleration in the x, y, and z directions.
 * @param listener SensorEventListener object.
 * @return a Thread object.
 */
private Thread createStreamingThread(List<float[]> sensorValues, SensorEventListener listener) {
    return new Thread(() -> {
        for (float[] accelValues : sensorValues) {
            SensorEvent mockEvent = mock(SensorEvent.clreplaced);
            try {
                Field sensorValuesField = SensorEvent.clreplaced.getField("values");
                sensorValuesField.setAccessible(true);
                sensorValuesField.set(mockEvent, accelValues);
                listener.onSensorChanged(mockEvent);
                Sleep.milliseconds(SENSOR_DATA_POLLING_INTERVAL_MS);
            } catch (NoSuchFieldException | IllegalAccessException reflectionFailure) {
                throw new RuntimeException(reflectionFailure);
            }
        }
    });
}

19 Source : MagneticStrengthSensor.java
with Apache License 2.0
from arduino

/**
 * Clreplaced to get sensor data from the Magnetic sensor.
 */
public clreplaced MagneticStrengthSensor extends ScalarSensor {

    // For historical reasons, the ID is MagneticRotationSensor. Since this is not exposed to the
    // user, we will just not mind the inconsistency.
    public static final String ID = "MagneticRotationSensor";

    private SensorEventListener sensorEventListener;

    public MagneticStrengthSensor() {
        super(ID);
    }

    @Override
    protected SensorRecorder makeScalarControl(final StreamConsumer c, final SensorEnvironment environment, final Context context, final SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                final Clock clock = environment.getDefaultClock();
                sensorEventListener = new SensorEventListener() {

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        // The strength is the square root of the sum of the squares of the
                        // values in X, Y and Z.
                        c.addData(clock.getNow(), Math.sqrt(Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2)));
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
            }
        };
    }

    public static boolean isMagneticRotationSensorAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_MAGNETIC_FIELD);
    }
}

19 Source : LinearAccelerometerSensor.java
with Apache License 2.0
from arduino

/**
 * Clreplaced to get scalar, linear data from the linear accelerometer sensor by combining acceleration
 * in all three axis. The force of gravity is excluded.
 */
public clreplaced LinearAccelerometerSensor extends ScalarSensor {

    public static final String ID = "LinearAccelerometerSensor";

    private SensorEventListener sensorEventListener;

    public LinearAccelerometerSensor() {
        super(ID);
    }

    @Override
    protected SensorRecorder makeScalarControl(final StreamConsumer c, final SensorEnvironment environment, final Context context, final SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                final Clock clock = environment.getDefaultClock();
                sensorEventListener = new SensorEventListener() {

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        c.addData(clock.getNow(), Math.sqrt(event.values[0] * event.values[0] + event.values[1] * event.values[1] + event.values[2] * event.values[2]));
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_UI);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
            }
        };
    }

    public static boolean isLinearAccelerometerAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_LINEAR_ACCELERATION);
    }
}

19 Source : CompassSensor.java
with Apache License 2.0
from arduino

/**
 * Clreplaced to create a compreplaced sensor from the magnetic field and accelerometer.
 */
public clreplaced CompreplacedSensor extends ScalarSensor {

    public static final String ID = "CompreplacedSensor";

    private SensorEventListener sensorEventListener;

    public CompreplacedSensor() {
        super(ID);
    }

    @Override
    protected SensorRecorder makeScalarControl(StreamConsumer c, SensorEnvironment environment, Context context, SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
                Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                final Clock clock = environment.getDefaultClock();
                sensorEventListener = new SensorEventListener() {

                    private float[] orientation = new float[3];

                    private float[] magneticRotation;

                    private float[] acceleration;

                    private float[] rotation = new float[9];

                    private float[] inclination = new float[9];

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                            acceleration = event.values;
                        } else {
                            magneticRotation = event.values;
                        }
                        // Update data as long as we have a value for both. This is the highest
                        // rate of update.
                        // If we want a slower rate, we can update when *both* values have changed,
                        // or only when magneticRotation changes, for example.
                        if (acceleration == null || magneticRotation == null) {
                            return;
                        }
                        boolean hasRotation = SensorManager.getRotationMatrix(rotation, inclination, acceleration, magneticRotation);
                        if (hasRotation) {
                            SensorManager.getOrientation(rotation, orientation);
                            // Use a positive angle in degrees between 0 and 360.
                            c.addData(clock.getNow(), 360 - (360 - (Math.toDegrees(orientation[0]))) % 360);
                        }
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
                sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
            }
        };
    }

    public static boolean isCompreplacedSensorAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_ACCELEROMETER) && availableSensors.isSensorAvailable(Sensor.TYPE_MAGNETIC_FIELD);
    }
}

19 Source : BarometerSensor.java
with Apache License 2.0
from arduino

/**
 * Clreplaced to get sensor data from the Pressure Sensor (barometer).
 */
public clreplaced BarometerSensor extends ScalarSensor {

    public static final String ID = "BarometerSensor";

    private SensorEventListener sensorEventListener;

    public BarometerSensor() {
        super(ID);
    }

    @Override
    protected SensorRecorder makeScalarControl(final StreamConsumer c, final SensorEnvironment environment, final Context context, final SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                final Clock clock = environment.getDefaultClock();
                sensorEventListener = new SensorEventListener() {

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        // values[0]: Atmospheric pressure in hPa (millibar).
                        // 1 hPa == 1 millibar
                        c.addData(clock.getNow(), event.values[0]);
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_UI);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
            }
        };
    }

    public static boolean isBarometerSensorAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_PRESSURE);
    }
}

19 Source : AmbientTemperatureSensor.java
with Apache License 2.0
from arduino

/**
 * Clreplaced to get sensor data from the Ambient Temperature sensor.
 */
public clreplaced AmbientTemperatureSensor extends ScalarSensor {

    public static final String ID = "AmbientTemperatureSensor";

    private SensorEventListener sensorEventListener;

    public AmbientTemperatureSensor() {
        super(ID);
    }

    @Override
    protected SensorRecorder makeScalarControl(final StreamConsumer c, final SensorEnvironment environment, final Context context, final SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                final Clock clock = environment.getDefaultClock();
                sensorEventListener = new SensorEventListener() {

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        c.addData(clock.getNow(), event.values[0]);
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
            }
        };
    }

    public static boolean isAmbientTemperatureSensorAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_AMBIENT_TEMPERATURE);
    }
}

19 Source : AccelerometerSensor.java
with Apache License 2.0
from arduino

public clreplaced AccelerometerSensor extends ScalarSensor {

    private Axis axis;

    public enum Axis {

        X(0, "AccX"), Y(1, "AccY"), Z(2, "AccZ");

        private final int valueIndex;

        private String databaseTag;

        Axis(int valueIndex, String databaseTag) {
            this.valueIndex = valueIndex;
            this.databaseTag = databaseTag;
        }

        public float getValue(SensorEvent event) {
            return event.values[valueIndex];
        }

        public String getSensorId() {
            return databaseTag;
        }
    }

    private SensorEventListener sensorEventListener;

    public AccelerometerSensor(Axis axis) {
        super(axis.getSensorId());
        this.axis = axis;
    }

    @Override
    protected SensorRecorder makeScalarControl(final StreamConsumer c, final SensorEnvironment environment, final Context context, final SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                final Clock clock = environment.getDefaultClock();
                sensorEventListener = new SensorEventListener() {

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        c.addData(clock.getNow(), axis.getValue(event));
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_UI);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
            }
        };
    }

    public static boolean isAccelerometerAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_ACCELEROMETER);
    }
}

18 Source : SensorHeartTest.java
with Apache License 2.0
from yanzhenjie

/**
 * Created by Zhenjie Yan on 2018/1/25.
 */
clreplaced SensorHeartTest implements PermissionTest {

    private Context mContext;

    SensorHeartTest(Context context) {
        this.mContext = context;
    }

    @Override
    public boolean test() throws Throwable {
        SensorManager sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        try {
            Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
            sensorManager.registerListener(SENSOR_EVENT_LISTENER, heartRateSensor, 3);
            sensorManager.unregisterListener(SENSOR_EVENT_LISTENER, heartRateSensor);
        } catch (Throwable e) {
            PackageManager packageManager = mContext.getPackageManager();
            return !packageManager.hreplacedystemFeature(PackageManager.FEATURE_SENSOR_HEART_RATE);
        }
        return true;
    }

    private static final SensorEventListener SENSOR_EVENT_LISTENER = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
        }

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

18 Source : SensorActivityTest.java
with Apache License 2.0
from yanzhenjie

/**
 * Created by Zhenjie Yan on 2018/1/25.
 */
clreplaced SensorActivityTest implements PermissionTest {

    private Context mContext;

    SensorActivityTest(Context context) {
        this.mContext = context;
    }

    @Override
    public boolean test() throws Throwable {
        SensorManager sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        try {
            Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
            sensorManager.registerListener(SENSOR_EVENT_LISTENER, heartRateSensor, 3);
            sensorManager.unregisterListener(SENSOR_EVENT_LISTENER, heartRateSensor);
        } catch (Throwable e) {
            PackageManager packageManager = mContext.getPackageManager();
            return !packageManager.hreplacedystemFeature(PackageManager.FEATURE_SENSOR_STEP_DETECTOR);
        }
        return true;
    }

    private static final SensorEventListener SENSOR_EVENT_LISTENER = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
        }

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

18 Source : ProximityService.java
with GNU General Public License v3.0
from socoolby

/**
 * Alway zuo,never die.
 * Created by socoolby on 16/04/2017.
 */
public clreplaced ProximityService extends Service {

    private final static String TAG = ProximityService.clreplaced.getSimpleName();

    private SensorManager mSensorManager;

    private SensorEventListener mSensorListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            float[] its = sensorEvent.values;
            Log.d(TAG, String.format("its %f %f %f len:,%d", its[0], its[1], its[2], its.length));
            if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
                if (FuncUnit.isForeground(ClockApplication.getContext(), MainActivity.clreplaced.getName())) {
                    if (its[0] == 0.0) {
                        System.out.println("Hand stay");
                        if (ScreenManager.isScreenOn()) {
                            ScreenManager.systemLock(ClockApplication.getInstance().getMainActivity());
                        } else {
                            ScreenManager.systemUnLock();
                        }
                    } else {
                        System.out.println("Hand leave...");
                    }
                }
            }
        }

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

    @Override
    public void onCreate() {
        super.onCreate();
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mSensorManager.unregisterListener(mSensorListener);
        super.onDestroy();
    }
}

18 Source : OrientationChangedPresenter.java
with Apache License 2.0
from Samsung

public clreplaced OrientationChangedPresenter implements Presenter {

    private static final float Y_DELTA_FOR_DETECT_LANDSCAPE = 6.5f;

    private static final String TAG = OrientationChangedPresenter.clreplaced.getSimpleName();

    private SensorEventListener orientationListener = new SensorEventListener() {

        int orientation = -1;

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (Math.abs(event.values[1]) < Y_DELTA_FOR_DETECT_LANDSCAPE) {
                if (orientation != EventSubCodes.SAMSUNG_DEVICE_ORIENTATION_LANDSCAPE) {
                    Log.d(TAG, "Landscape");
                }
                orientation = EventSubCodes.SAMSUNG_DEVICE_ORIENTATION_LANDSCAPE;
            } else {
                if (orientation != EventSubCodes.SAMSUNG_DEVICE_ORIENTATION_PORTRAIT) {
                    Log.d(TAG, "Portrait");
                }
                orientation = EventSubCodes.SAMSUNG_DEVICE_ORIENTATION_PORTRAIT;
            }
            if (previousOrientation != orientation) {
                MBApp application = MBApp.getApp();
                Intent intent = new Intent(application, IPCService.clreplaced);
                intent.putExtra(IPCConstants.INTENT_TYPE, EventCategories.IPC_BLE_NOTIFICATION_CHARACTERISTIC_CHANGED);
                intent.putExtra(IPCConstants.INTENT_CHARACTERISTIC_MESSAGE, Utils.makeMicroBitValue(EventCategories.SAMSUNG_DEVICE_INFO_ID, orientation));
                application.startService(intent);
                previousOrientation = orientation;
            }
        }

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

    private int previousOrientation = -1;

    private SensorManager sensorManager;

    private boolean isRegistered;

    public OrientationChangedPresenter() {
        sensorManager = (SensorManager) MBApp.getApp().getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    public void start() {
        if (!isRegistered) {
            sensorManager.registerListener(orientationListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            isRegistered = true;
        }
    }

    @Override
    public void stop() {
        if (isRegistered) {
            sensorManager.unregisterListener(orientationListener);
            isRegistered = false;
        }
    }

    @Override
    public void destroy() {
        stop();
    }
}

18 Source : GyroHelper.java
with Apache License 2.0
from saki4510t

public clreplaced GyroHelper {

    // FIXME 実働時はfalseにすること
    private static final boolean DEBUG = false;

    private static final String TAG = GyroHelper.clreplaced.getSimpleName();

    private static final int[] SENSOR_TYPES = { Sensor.TYPE_MAGNETIC_FIELD, Sensor.TYPE_GRAVITY, Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GYROSCOPE };

    private final Object mSync = new Object();

    private final WeakReference<Context> mWeakContext;

    private SensorManager mSensorManager;

    private boolean mRegistered;

    // 画面の向き
    private int mRotation;

    // センサー値同期用
    private final Object mSensorSync = new Object();

    // 磁気[μT]
    private final float[] mMagnetValues = new float[3];

    // 重力[m/s^2]
    private final float[] mGravityValues = new float[3];

    // 方位[-180,+180][度]
    private final float[] mAzimuthValues = new float[3];

    // 加速度[m/s^2]
    private final float[] mAccelValues = new float[3];

    // ジャイロ[radian/s]
    private final float[] mGyroValues = new float[3];

    public GyroHelper(@NonNull final Context context) {
        mWeakContext = new WeakReference<Context>(context);
        synchronized (mSync) {
            mSensorManager = ContextUtils.requireSystemService(context, SensorManager.clreplaced);
        }
    }

    public void release() {
        synchronized (mSync) {
            mSensorManager = null;
        }
    }

    /**
     * 磁気センサー・加速度センサー等を読み取り開始
     */
    public void start() {
        synchronized (mSync) {
            final Context context = mWeakContext.get();
            if ((mSensorManager == null) || (context == null)) {
                throw new IllegalStateException("already released");
            }
            for (int i = 0; i < 3; i++) {
                mMagnetValues[i] = mGravityValues[i] = mAzimuthValues[i] = 0;
                mAccelValues[i] = mGyroValues[i] = 0;
            }
            // 重力センサーがあればそれを使う。なければ加速度センサーで代用する
            boolean hasGravity = false;
            mRegistered = true;
            for (final int sensor_type : SENSOR_TYPES) {
                final List<Sensor> sensors = mSensorManager.getSensorList(sensor_type);
                if ((sensors != null) && (sensors.size() > 0)) {
                    if (sensor_type == Sensor.TYPE_GRAVITY) {
                        Log.i(TAG, "hasGravity");
                        hasGravity = true;
                    }
                    if (!hasGravity || (sensor_type != Sensor.TYPE_ACCELEROMETER)) {
                        mSensorManager.registerListener(mSensorEventListener, sensors.get(0), SensorManager.SENSOR_DELAY_GAME);
                    }
                } else {
                    Log.i(TAG, String.format("no sensor for sensor type %d", sensor_type));
                }
            }
        }
    }

    /**
     * 磁気センサー・加速度センサー等からの読み取り終了
     */
    public void stop() {
        synchronized (mSync) {
            if (mRegistered && (mSensorManager != null)) {
                try {
                    mSensorManager.unregisterListener(mSensorEventListener);
                } catch (final Exception e) {
                // ignore
                }
            }
            mRegistered = false;
        }
    }

    public void setScreenRotation(final int rotation) {
        mRotation = rotation;
    }

    /**
     * 方位角を取得
     * @return
     */
    public float getAzimuth() {
        return mAzimuthValues[0];
    }

    /**
     * 左右への傾きを取得, XXX 前後と左右が入れ替わってるかも
     * @return
     */
    public float getPan() {
        return mAzimuthValues[1];
    }

    /**
     * 前後の傾きを取得, XXX 前後と左右が入れ替わってるかも
     * @return
     */
    public float getTilt() {
        return mAzimuthValues[2];
    }

    private final SensorEventListener mSensorEventListener = new SensorEventListener() {

        /**
         * ハイパスフィルターを通して値をセットする
         * @param values 値を保持するためのfloat配列
         * @param new_values 新しい値を渡すためのfloat配列
         * @param alpha フィルター定数(alpha=t/(t+dt)
         */
        private void highPreplacedFilter(final float[] values, final float[] new_values, final float alpha) {
            values[0] = alpha * values[0] + (1 - alpha) * new_values[0];
            values[1] = alpha * values[1] + (1 - alpha) * new_values[1];
            values[2] = alpha * values[2] + (1 - alpha) * new_values[2];
        }

        private final float[] outR = new float[16];

        private final float[] outR2 = new float[16];

        private void getOrientation(final float[] rotateMatrix, final float[] result) {
            switch(mRotation) {
                case Surface.ROTATION_0:
                    SensorManager.getOrientation(rotateMatrix, result);
                    return;
                case Surface.ROTATION_90:
                    SensorManager.remapCoordinateSystem(rotateMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, outR);
                    break;
                case Surface.ROTATION_180:
                    SensorManager.remapCoordinateSystem(rotateMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, outR2);
                    SensorManager.remapCoordinateSystem(outR2, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, outR);
                    break;
                case Surface.ROTATION_270:
                    SensorManager.remapCoordinateSystem(outR, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_MINUS_X, outR);
                    break;
            }
            SensorManager.getOrientation(outR, result);
        }

        private static final float TO_DEGREE = (float) (180 / Math.PI);

        // 回転行列
        private final float[] mRotateMatrix = new float[16];

        // 傾斜行列
        private final float[] mInclinationMatrix = new float[16];

        /**
         * センサーの値が変化した時のコールバック
         * @param event
         */
        @Override
        public void onSensorChanged(final SensorEvent event) {
            if (DEBUG)
                Log.v(TAG, "onSensorChanged:" + event);
            final float[] values = event.values;
            final int type = event.sensor.getType();
            switch(type) {
                case // 磁気センサー
                Sensor.TYPE_MAGNETIC_FIELD:
                    synchronized (mSensorSync) {
                        // ハイパスフィルターを通して取得
                        // alpha=t/(t+dt), dt≒20msec@SENSOR_DELAY_GAME, tはローパスフィルタの時定数(t=80)
                        highPreplacedFilter(mMagnetValues, values, 0.8f);
                        System.arraycopy(values, 0, mMagnetValues, 0, 3);
                        // 磁気センサーの値と重力センサーの値から方位を計算
                        SensorManager.getRotationMatrix(mRotateMatrix, mInclinationMatrix, mGravityValues, mMagnetValues);
                        getOrientation(mRotateMatrix, mAzimuthValues);
                        mAzimuthValues[0] *= TO_DEGREE;
                        mAzimuthValues[1] *= TO_DEGREE;
                        mAzimuthValues[2] *= TO_DEGREE;
                    }
                    break;
                case // 重力センサー
                Sensor.TYPE_GRAVITY:
                    synchronized (mSensorSync) {
                        System.arraycopy(values, 0, mGravityValues, 0, 3);
                    }
                    break;
                case // 加速度センサー
                Sensor.TYPE_ACCELEROMETER:
                    synchronized (mSensorSync) {
                        System.arraycopy(values, 0, mAccelValues, 0, 3);
                        // 重力センサーが無い時は加速度センサーで代用
                        System.arraycopy(values, 0, mGravityValues, 0, 3);
                    }
                    break;
                case // ジャイロセンサー
                Sensor.TYPE_GYROSCOPE:
                    synchronized (mSensorSync) {
                        System.arraycopy(values, 0, mGyroValues, 0, 3);
                    }
                    break;
                default:
                    if (DEBUG)
                        Log.v(TAG, "onSensorChanged:" + String.format(Locale.US, "その他%d(%f,%f,%f)", type, values[0], values[1], values[2]));
                    break;
            }
        }

        /**
         * センサーの精度が変更された時のコールバック
         * @param sensor
         * @param accuracy
         */
        @Override
        public void onAccuracyChanged(final Sensor sensor, int accuracy) {
        }
    };
}

18 Source : MainActivity.java
with Apache License 2.0
from retomeier

public clreplaced MainActivity extends AppCompatActivity {

    private static final String TAG = "CH16_SNIPPETS";

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

    private void listing16_1_2_3_4() {
        // Listing 16-1: Determining if a type of sensor is available
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null) {
        // TODO Barometer is available.
        } else {
        // TODO No barometer is available.
        }
        // Listing 16-2: Sensor Event Listener skeleton code
        final SensorEventListener mySensorEventListener = new SensorEventListener() {

            public void onSensorChanged(SensorEvent sensorEvent) {
            // TODO React to new Sensor result.
            }

            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO React to a change in Sensor accuracy.
            }
        };
        // Listing 16-3: Registering a Sensor Event Listener
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        sensorManager.registerListener(mySensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Listing 16-4: Registering a Sensor Event Listener with a maximum Latency
            Sensor slowSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
            sensorManager.registerListener(mySensorEventListener, slowSensor, SensorManager.SENSOR_DELAY_NORMAL, 10000000);
        }
    }

    /*
   * Listing 16-5: Trigger Event Listener skeleton code
   */
    TriggerEventListener triggerEventListener = new TriggerEventListener() {

        @Override
        public void onTrigger(TriggerEvent event) {
        // TODO React to trigger event.
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void listing16_6() {
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // Listing 16-6: Registering a Trigger Event Listener
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
        sensorManager.requestTriggerSensor(triggerEventListener, sensor);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void listing16_7() {
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
        // Listing 16-7: Registering a Sensor Event Callback to receive Sensor Additional Info
        SensorEventCallback sensorEventCallback = new SensorEventCallback() {

            @Override
            public void onSensorChanged(SensorEvent event) {
                super.onSensorChanged(event);
            // TODO Monitor Sensor changes.
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                super.onAccuracyChanged(sensor, accuracy);
            // TODO React to a change in Sensor accuracy.
            }

            @Override
            public void onFlushCompleted(Sensor sensor) {
                super.onFlushCompleted(sensor);
            // FIFO of this sensor has been flushed.
            }

            @Override
            public void onSensorAdditionalInfo(SensorAdditionalInfo info) {
                super.onSensorAdditionalInfo(info);
            // TODO Monitor additional sensor information.
            }
        };
        sensorManager.registerListener(sensorEventCallback, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void listing16_8() {
        // Listing 16-8: Finding the screen orientation relative to the natural orientation
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int rotation = display.getRotation();
        switch(rotation) {
            // Natural
            case (Surface.ROTATION_0):
                break;
            // On its left side
            case (Surface.ROTATION_90):
                break;
            // Upside down
            case (Surface.ROTATION_180):
                break;
            // On its right side
            case (Surface.ROTATION_270):
                break;
            default:
                break;
        }
    }

    private void listing16_9() {
        final SensorEventListener mySensorEventListener = new SensorEventListener() {

            // Listing 16-10: Calculating the device orientation using the rotation vector
            public void onSensorChanged(SensorEvent sensorEvent) {
                float[] rotationMatrix = new float[9];
                float[] orientation = new float[3];
                // Convert the result Vector to a Rotation Matrix.
                SensorManager.getRotationMatrixFromVector(rotationMatrix, sensorEvent.values);
                // Extract the orientation from the Rotation Matrix.
                SensorManager.getOrientation(rotationMatrix, orientation);
                // Yaw
                Log.d(TAG, "Yaw: " + orientation[0]);
                // Pitch
                Log.d(TAG, "Pitch: " + orientation[1]);
                // Roll
                Log.d(TAG, "Roll: " + orientation[2]);
            }

            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }
        };
        // Listing 16-9: Monitoring an accelerometer sensor
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        int sensorType = Sensor.TYPE_ACCELEROMETER;
        sm.registerListener(mySensorEventListener, sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
    }

    /*
   * Listing 16-11: Monitoring the accelerometer and magnetometer
   */
    private float[] mAccelerometerValues;

    private float[] mMagneticFieldValues;

    final SensorEventListener mCombinedSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent sensorEvent) {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
                mAccelerometerValues = sensorEvent.values;
            if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
                mMagneticFieldValues = sensorEvent.values;
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    private void registerCombinedListener() {
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor aSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor mfSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        sm.registerListener(mCombinedSensorListener, aSensor, SensorManager.SENSOR_DELAY_UI);
        sm.registerListener(mCombinedSensorListener, mfSensor, SensorManager.SENSOR_DELAY_UI);
    }

    private void listing16_12() {
        // Listing 16-12: Finding the current orientation using the accelerometer and magnetometer
        float[] values = new float[3];
        float[] R = new float[9];
        SensorManager.getRotationMatrix(R, null, mAccelerometerValues, mMagneticFieldValues);
        SensorManager.getOrientation(R, values);
        // Convert from radians to degrees if preferred.
        // Azimuth
        values[0] = (float) Math.toDegrees(values[0]);
        // Pitch
        values[1] = (float) Math.toDegrees(values[1]);
        // Roll
        values[2] = (float) Math.toDegrees(values[2]);
    }

    private long lastTime = 0;

    private void listing16_13() {
        // Listing 16-13: Calculating an orientation change using the gyroscope Sensor
        final float nanosecondsPerSecond = 1.0f / 100000000.0f;
        final float[] angle = new float[3];
        SensorEventListener myGyroListener = new SensorEventListener() {

            public void onSensorChanged(SensorEvent sensorEvent) {
                if (lastTime != 0) {
                    final float dT = (sensorEvent.timestamp - lastTime) * nanosecondsPerSecond;
                    angle[0] += sensorEvent.values[0] * dT;
                    angle[1] += sensorEvent.values[1] * dT;
                    angle[2] += sensorEvent.values[2] * dT;
                }
                lastTime = sensorEvent.timestamp;
            }

            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }
        };
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        int sensorType = Sensor.TYPE_GYROSCOPE;
        sm.registerListener(myGyroListener, sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void listing16_14() {
        float[] values = new float[3];
        float[] inR = new float[9];
        float[] outR = new float[9];
        SensorManager.getRotationMatrix(inR, null, mAccelerometerValues, mMagneticFieldValues);
        // Listing 16-14: Remapping the orientation reference frame based on the natural orientation of the device
        // Determine the current orientation relative to the natural orientation
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int rotation = display.getRotation();
        int x_axis = SensorManager.AXIS_X;
        int y_axis = SensorManager.AXIS_Y;
        switch(rotation) {
            case (Surface.ROTATION_0):
                break;
            case (Surface.ROTATION_90):
                x_axis = SensorManager.AXIS_Y;
                y_axis = SensorManager.AXIS_MINUS_X;
                break;
            case (Surface.ROTATION_180):
                y_axis = SensorManager.AXIS_MINUS_Y;
                break;
            case (Surface.ROTATION_270):
                x_axis = SensorManager.AXIS_MINUS_Y;
                y_axis = SensorManager.AXIS_X;
                break;
            default:
                break;
        }
        SensorManager.remapCoordinateSystem(inR, x_axis, y_axis, outR);
        // Obtain the new, remapped, orientation values.
        SensorManager.getOrientation(outR, values);
    }

    private void listing16_15() {
        // Listing 16-15: Finding the current alreplacedude using the barometer Sensor
        final SensorEventListener myPressureListener = new SensorEventListener() {

            public void onSensorChanged(SensorEvent sensorEvent) {
                if (sensorEvent.sensor.getType() == Sensor.TYPE_PRESSURE) {
                    float currentPressure = sensorEvent.values[0];
                    // Calculate alreplacedude
                    float alreplacedude = SensorManager.getAlreplacedude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, currentPressure);
                }
            }

            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }
        };
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        int sensorType = Sensor.TYPE_PRESSURE;
        sm.registerListener(myPressureListener, sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
    }

    /*
   * Listing 16-16: Connecting a Sensor Event Listener to a heart rate monitor
   */
    private static final String HR_TAG = "HEART_RATE";

    private static final int BODY_SENSOR_PERMISSION_REQUEST = 1;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
    private void connectHeartRateSensor() {
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS);
        if (permission == PERMISSION_GRANTED) {
            // If permission granted, connect the event listener.
            doConnectHeartRateSensor();
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BODY_SENSORS)) {
            // TODO: Display additional rationale for the requested permission.
            }
            // Request the permission
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.BODY_SENSORS }, BODY_SENSOR_PERMISSION_REQUEST);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == BODY_SENSOR_PERMISSION_REQUEST && grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
            // If permission granted, connect the heart rate sensor.
            doConnectHeartRateSensor();
        } else {
            Log.d(TAG, "Body Sensor access permission denied.");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
    private void doConnectHeartRateSensor() {
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor heartRateSensor = sm.getDefaultSensor(Sensor.TYPE_HEART_RATE);
        if (heartRateSensor == null)
            Log.d(TAG, "No Heart Rate Sensor Detected.");
        else {
            sm.registerListener(mHeartRateListener, heartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    final SensorEventListener mHeartRateListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent sensorEvent) {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_HEART_RATE) {
                if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_NO_CONTACT || sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
                    Log.d(TAG, "Heart Rate Monitor not in contact or unreliable");
                } else {
                    float currentHeartRate = sensorEvent.values[0];
                    Log.d(TAG, "Heart Rate: " + currentHeartRate);
                }
            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
}

18 Source : CompassActivity.java
with Apache License 2.0
from retomeier

public clreplaced CompreplacedActivity extends AppCompatActivity {

    private CompreplacedView mCompreplacedView;

    private SensorManager mSensorManager;

    private int mScreenRotation;

    private float[] mNewestValues;

    private void updateOrientation(float[] values) {
        if (mCompreplacedView != null) {
            mCompreplacedView.setBearing(values[0]);
            mCompreplacedView.setPitch(values[1]);
            mCompreplacedView.setRoll(-values[2]);
            mCompreplacedView.invalidate();
        }
    }

    private float[] calculateOrientation(float[] values) {
        float[] rotationMatrix = new float[9];
        float[] remappedMatrix = new float[9];
        float[] orientation = new float[3];
        // Determine the rotation matrix
        SensorManager.getRotationMatrixFromVector(rotationMatrix, values);
        // Remap the coordinates based on the natural device orientation.
        int x_axis = SensorManager.AXIS_X;
        int y_axis = SensorManager.AXIS_Y;
        switch(mScreenRotation) {
            case (Surface.ROTATION_90):
                x_axis = SensorManager.AXIS_Y;
                y_axis = SensorManager.AXIS_MINUS_X;
                break;
            case (Surface.ROTATION_180):
                y_axis = SensorManager.AXIS_MINUS_Y;
                break;
            case (Surface.ROTATION_270):
                x_axis = SensorManager.AXIS_MINUS_Y;
                y_axis = SensorManager.AXIS_X;
                break;
            default:
                break;
        }
        SensorManager.remapCoordinateSystem(rotationMatrix, x_axis, y_axis, remappedMatrix);
        // Obtain the current, corrected orientation.
        SensorManager.getOrientation(remappedMatrix, orientation);
        // Convert from Radians to Degrees.
        values[0] = (float) Math.toDegrees(orientation[0]);
        values[1] = (float) Math.toDegrees(orientation[1]);
        values[2] = (float) Math.toDegrees(orientation[2]);
        return values;
    }

    private final SensorEventListener mSensorEventListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent sensorEvent) {
            mNewestValues = calculateOrientation(sensorEvent.values);
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    private void updateGUI() {
        runOnUiThread(new Runnable() {

            public void run() {
                updateOrientation(mNewestValues);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compreplaced);
        mCompreplacedView = findViewById(R.id.compreplacedView);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        mScreenRotation = display.getRotation();
        mNewestValues = new float[] { 0, 0, 0 };
        Timer updateTimer = new Timer("compreplacedUpdate");
        updateTimer.scheduleAtFixedRate(new TimerTask() {

            public void run() {
                updateGUI();
            }
        }, 0, 1000 / 60);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor rotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
        mSensorManager.registerListener(mSensorEventListener, rotationVector, SensorManager.SENSOR_DELAY_FASTEST);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mSensorEventListener);
    }
}

18 Source : ShakeEventHandler.java
with MIT License
from qunarcorp

/**
 * Created by zhaokai on 15-8-28.
 */
public clreplaced ShakeEventHandler {

    public static final String TAG = "ShakeEventHandler";

    private final int SHAKE_THRESHOLD = 24;

    // /** 决定是否是摇晃的最小值. */
    // /**
    // * 一次摇晃需要的最少的方向改变次数
    // */
    private static final int MIN_DIRECTION_CHANGE = 3;

    // /** 动作之间的最长暂定时间 */
    private static final int MAX_PAUSE_BETHWEEN_DIRECTION_CHANGE = 330;

    long lastUpdateTime = 0;

    ArrayList<OnShakeListener> listeners;

    // 超时时间,如果超过2s则清空次数
    private int changeTime = 0;

    private SensorManager mSensorManager;

    private Sensor sensor;

    private float lastX, lastY, lastZ;

    private SensorEventListener sensorEventListener;

    public ShakeEventHandler(Context context) {
        listeners = new ArrayList<>();
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        sensorEventListener = new SensorEventListener() {

            @Override
            public synchronized void onSensorChanged(SensorEvent event) {
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastUpdateTime > MAX_PAUSE_BETHWEEN_DIRECTION_CHANGE) {
                    changeTime = 0;
                }
                float getX = event.values[0];
                float getY = event.values[1];
                float getZ = event.values[2];
                if (Math.round(getX) != 0 && Math.round(getY) != 0 && Math.round(getZ) != 0) {
                    lastUpdateTime = currentTime;
                    float differX = getX - lastX;
                    float differY = getY - lastY;
                    float differZ = getZ - lastZ;
                    double differ = Math.sqrt(differX * differX + differY * differY + differZ * differZ);
                    if (differ > SHAKE_THRESHOLD) {
                        LogUtil.d(TAG, "the last acceleration is\t" + "[x:" + lastX + "\ty:" + lastY + "\tz:" + lastZ + "]");
                        LogUtil.d(TAG, "the acceleration is\t" + "[x:" + getX + "\ty:" + getY + "\tz:" + getZ + "]");
                        LogUtil.d(TAG, "the differ is\t" + differ);
                        lastX = getX;
                        lastY = getY;
                        lastZ = getZ;
                        if (++changeTime > MIN_DIRECTION_CHANGE) {
                            changeTime = 0;
                            notifyDataChanged();
                        }
                    }
                }
            }

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

    public void start() {
        if (mSensorManager == null || sensor == null || !mSensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL)) {
            throw new UnsupportedOperationException("设备不支持该操作");
        }
    }

    public void stop() {
        if (listeners != null) {
            listeners.clear();
        }
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(sensorEventListener);
        }
    }

    public void registerOnShakeListener(OnShakeListener listener) {
        if (listeners != null) {
            listeners.add(listener);
        }
    }

    private void notifyDataChanged() {
        if (listeners != null) {
            for (OnShakeListener listener : listeners) {
                listener.onShake();
            }
        }
    }

    public interface OnShakeListener {

        /**
         * 当手机摇晃的时候调用
         */
        void onShake();
    }
}

18 Source : SensorUpdatesProvider.java
with Apache License 2.0
from PrivacyStreams

/**
 * Provide a live stream of sensor updates.
 */
abstract clreplaced SensorUpdatesProvider extends PStreamProvider {

    private transient SensorEventListener sensorListener;

    private transient SensorManager sensorManager;

    private transient Sensor sensor;

    private final int sensorType;

    private final int sensorDelay;

    SensorUpdatesProvider(int sensorType, int sensorDelay) {
        this.sensorType = sensorType;
        this.sensorDelay = sensorDelay;
        this.addParameters(sensorType, sensorDelay);
    }

    protected abstract void handleSensorEvent(SensorEvent sensorEvent);

    protected void handleAccuracyChange(Sensor sensor, int accuracy) {
    // Do nothing.
    }

    @Override
    protected void onCancel(UQI uqi) {
        super.onCancel(uqi);
        sensorManager.unregisterListener(sensorListener);
    }

    @Override
    protected void provide() {
        sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(sensorType);
        sensorListener = new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent event) {
                handleSensorEvent(event);
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                handleAccuracyChange(sensor, accuracy);
            }
        };
        sensorManager.registerListener(sensorListener, sensor, sensorDelay);
    }
}

18 Source : HeartRateService.java
with GNU General Public License v3.0
from NightscoutFoundation

/**
 * Created by jamorham on 12/01/2018.
 *
 * Intent service to measure heart rate using wear sensor
 *
 * beware when modifying this that each time the intent fires it is a new instance
 * so things to persist between firings need to be static or maintained independently
 */
public clreplaced HeartRateService extends IntentService {

    public static final String TAG = "HeartRateService";

    private static final long TIME_WAIT_FOR_READING = Constants.SECOND_IN_MS * 30;

    // TODO review or allow configurable period
    public static final long READING_PERIOD = Constants.SECOND_IN_MS * 300;

    private static final long MINIMUM_READING_PERIOD = Constants.SECOND_IN_MS * 30;

    private static final int ELEVATED_BPM = 100;

    private static final String ELEVATED_MARKER = "elevated-heart-marker";

    private static final String LAST_READING_PERIOD = "heart-last-period";

    private static final int BATCH_LATENCY_1s = 1000000;

    // moto 360 sensor
    private static final int TYPE_PreplacedIVE_WELLNESS_SENSOR = 65538;

    private static PendingIntent pendingIntent;

    private static long start_measuring_time = 0;

    private static long wakeup_time = 0;

    // KS
    private static boolean mSensorPermissionApproved;

    private static SensorManager mSensorManager;

    // event receiver when we get notified of a heart rate measurement
    // elevated readings result in more frequent sensor readings, to eliminate spurious values
    // and provide more detail during periods of exercise
    private static final SensorEventListener mHeartRateListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            final PowerManager.WakeLock wl = JoH.getWakeLock("heartrate-event", 60000);
            try {
                final int type = event.sensor.getType();
                if (type == android.hardware.Sensor.TYPE_HEART_RATE) {
                    try {
                        float mHeartRateFloat = event.values[0];
                        final int HeartRateBpm = Math.round(mHeartRateFloat);
                        if (HeartRateBpm > 30) {
                            android.util.Log.d(TAG, "HeartRate: " + HeartRateBpm + " " + event.sensor.getName() + " " + event.accuracy + " " + event.timestamp);
                            HeartRate.create(JoH.tsl(), HeartRateBpm, event.accuracy);
                            if (JoH.ratelimit("reschedule heart rate", 3)) {
                                stopHeartRateMeasurement();
                                final boolean elevated = (HeartRateBpm > ELEVATED_BPM);
                                long next_reading_period = READING_PERIOD;
                                if (elevated) {
                                    if (PersistentStore.getBoolean(ELEVATED_MARKER)) {
                                        // back off 30 seconds for each high reading up to half of reading period, reset to minimum if somehow we get 0 back from store
                                        next_reading_period = Math.max(MINIMUM_READING_PERIOD, Math.min(PersistentStore.getLong(LAST_READING_PERIOD) + (30 * Constants.SECOND_IN_MS), READING_PERIOD / 2));
                                    } else {
                                        // last reading was not elevated but this one is, move to minimum period
                                        next_reading_period = MINIMUM_READING_PERIOD;
                                        PersistentStore.setBoolean(ELEVATED_MARKER, true);
                                    }
                                    // last reading period becomes significant now and will likely have changed at this point
                                    PersistentStore.setLong(LAST_READING_PERIOD, next_reading_period);
                                } else {
                                    setElevatedMarkerFalseIfItWasTrue();
                                }
                                scheduleWakeUp(next_reading_period, "got reading - await next, elevated: " + elevated + " period: " + next_reading_period);
                                if (JoH.ratelimit("heart-resync", 20)) {
                                    // force sync
                                    Inevitable.task("request-data", 1000, () -> ListenerService.requestData(xdrip.getAppContext()));
                                }
                            // 
                            }
                        } else {
                            if (start_measuring_time > 0) {
                                UserError.Log.d(TAG, "Heartrate: too low to accept: " + HeartRateBpm);
                            // scheduleWakeUp(10000, "bad reading - schedule timeout"); // don't need to schedule as we will have a timeout monitor pending
                            } else {
                                UserError.Log.d(TAG, "We are supposed to be shutdown so not scheduling anything: rate: " + HeartRateBpm);
                            }
                        }
                    } catch (Exception e) {
                        android.util.Log.e(TAG, "HeartRate Exception: ", e);
                    }
                } else {
                    UserError.Log.e(TAG, "onSensorChanged: heart unknown sensor type! " + type);
                }
            } finally {
                JoH.releaseWakeLock(wl);
            }
        }

        @Override
        public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {
        }
    };

    public HeartRateService() {
        super("HeartRateService");
    }

    public static void scheduleWakeUp(long future, final String info) {
        if (Pref.getBoolean("use_wear_heartrate", true)) {
            if (future < 0)
                future = 5000;
            UserError.Log.d(TAG, "Scheduling wakeup @ " + JoH.dateTimeText(JoH.tsl() + future) + " (" + info + ")");
            if (pendingIntent == null)
                pendingIntent = PendingIntent.getService(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), HeartRateService.clreplaced), 0);
            wakeup_time = JoH.tsl() + future;
            JoH.wakeUpIntent(xdrip.getAppContext(), future, pendingIntent);
        } else {
            UserError.Log.d(TAG, "Service disabled so not scheduling a wakeup");
            if (start_measuring_time > 0) {
                // shut down if running
                stopHeartRateMeasurement();
            }
        }
    }

    private static synchronized void stopHeartRateMeasurement() {
        UserError.Log.i(TAG, "stopHeartRateMeasurement");
        start_measuring_time = 0;
        try {
            if (mSensorManager != null) {
                UserError.Log.i(TAG, "stopHeartRateMeasurement STOP Event listener for heart rate sensor register");
                mSensorManager.unregisterListener(mHeartRateListener);
            } else {
                UserError.Log.d(TAG, "Sensor Manager was null in stop!");
            }
        } catch (Exception e) {
            UserError.Log.i(TAG, "StopHeartMeasurement exception: " + e);
        }
    }

    public static synchronized DataMap getWearHeartSensorData(int count, long last_send_time, int min_count) {
        UserError.Log.d(TAG, "getWearHeartSensorData last_send_time:" + JoH.dateTimeText(last_send_time));
        if ((count != 0) || (JoH.ratelimit("heartrate-datamap", 5))) {
            HeartRate last_log = HeartRate.last();
            if (last_log != null) {
                UserError.Log.d(TAG, "getWearHeartSensorData last_log.timestamp:" + JoH.dateTimeText((long) last_log.timestamp));
            } else {
                UserError.Log.d(TAG, "getWearHeartSensorData HeartRate.last() = null:");
                return null;
            }
            if (last_log != null && last_send_time <= last_log.timestamp) {
                // startTime
                long last_send_success = last_send_time;
                UserError.Log.d(TAG, "getWearHeartSensorData last_send_time < last_bg.timestamp:" + JoH.dateTimeText((long) last_log.timestamp));
                List<HeartRate> logs = HeartRate.latestForGraph(count, last_send_time);
                if (!logs.isEmpty() && logs.size() > min_count) {
                    DataMap entries = dataMap(last_log);
                    final ArrayList<DataMap> dataMaps = new ArrayList<>(logs.size());
                    for (HeartRate log : logs) {
                        dataMaps.add(dataMap(log));
                        last_send_success = (long) log.timestamp;
                    }
                    // MOST IMPORTANT LINE FOR TIMESTAMP
                    entries.putLong("time", JoH.tsl());
                    entries.putDataMapArrayList("entries", dataMaps);
                    UserError.Log.i(TAG, "getWearHeartSensorData SYNCED up to " + JoH.dateTimeText(last_send_success) + " count = " + logs.size());
                    return entries;
                } else
                    UserError.Log.i(TAG, "getWearHeartSensorData SYNCED up to " + JoH.dateTimeText(last_send_success) + " count = 0");
            }
            return null;
        } else {
            UserError.Log.d(TAG, "Ratelimitted getWearHeartSensorData");
            return null;
        }
    }

    // this is pretty inefficient - maybe eventually replace with protobuf
    private static DataMap dataMap(HeartRate log) {
        final DataMap dataMap = new DataMap();
        final String json = log.toS();
        dataMap.putString("entry", json);
        return dataMap;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // service created
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            HeartRateJobService.enqueueWork();
        } else {
            realOnHandleIntent(intent);
        }
    }

    protected void realOnHandleIntent(Intent intent) {
        // service created
        UserError.Log.d(TAG, "RealOnHandleIntentEnter");
        final PowerManager.WakeLock wl = JoH.getWakeLock("heartrate-service", 60000);
        try {
            checkWhatToDo();
        } finally {
            JoH.releaseWakeLock(wl);
        }
        UserError.Log.d(TAG, "RealOnHandleIntentExit");
    }

    private void checkWhatToDo() {
        if (start_measuring_time == 0) {
            if (!restartHeartRateMeasurement()) {
                UserError.Log.d(TAG, "No heart rate sensor or disabled");
                return;
            }
            scheduleWakeUp(TIME_WAIT_FOR_READING + 1, "Started reading, recheck after timeout period");
        } else {
            if (JoH.msSince(start_measuring_time) > TIME_WAIT_FOR_READING) {
                stopHeartRateMeasurement();
                scheduleWakeUp(READING_PERIOD, "Failed to get last reading, retrying later");
                setElevatedMarkerFalseIfItWasTrue();
            } else {
                scheduleWakeUp(20 * Constants.SECOND_IN_MS, "Not sure what to do, trying again in a bit");
            }
        }
    }

    private synchronized boolean restartHeartRateMeasurement() {
        UserError.Log.d(TAG, "restartHeartRateMeasurement");
        stopHeartRateMeasurement();
        return startHeartRateMeasurement();
    }

    private synchronized boolean startHeartRateMeasurement() {
        UserError.Log.d(TAG, "startHeartRateMeasurement");
        if (Pref.getBoolean("use_wear_heartrate", true)) {
            if (mSensorManager == null)
                mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
            if (mSensorManager != null) {
                android.hardware.Sensor mHeartRateSensor = mSensorManager.getDefaultSensor(android.hardware.Sensor.TYPE_HEART_RATE);
                if ((mHeartRateSensor == null) && Build.MODEL.equals("Moto 360")) {
                    // Moto 360 makes heart rate sensor invisible until body sensor permission is approved
                    mHeartRateSensor = mSensorManager.getDefaultSensor(TYPE_PreplacedIVE_WELLNESS_SENSOR);
                    if (mHeartRateSensor != null) {
                        UserError.Log.d(TAG, "Using alternate wellness sensor");
                    }
                }
                if (mHeartRateSensor != null) {
                    if (checkSensorPermissions()) {
                        UserError.Log.d(TAG, "Enabling sensor");
                        start_measuring_time = JoH.tsl();
                        mSensorManager.registerListener(mHeartRateListener, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL, BATCH_LATENCY_1s);
                    } else {
                        UserError.Log.d(TAG, "No permission for heartrate");
                    }
                } else {
                    UserError.Log.d(TAG, "startMeasurement No Heart Rate Sensor found");
                    return false;
                }
            }
        } else {
            UserError.Log.d(TAG, "Heart rate feature disabled so not attempting to start");
            return false;
        }
        return true;
    }

    // wear requires runtime permission for this sensor
    private boolean checkSensorPermissions() {
        // KS
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return true;
        mSensorPermissionApproved = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BODY_SENSORS) == PackageManager.PERMISSION_GRANTED;
        UserError.Log.d(TAG, "checkSensorPermission  mSensorPermissionApproved:" + mSensorPermissionApproved);
        // Display Activity to get user permission
        if (!mSensorPermissionApproved) {
            if (JoH.ratelimit("sensor_permission", 20)) {
                Intent permissionIntent = new Intent(getApplicationContext(), SensorPermissionActivity.clreplaced);
                permissionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(permissionIntent);
            }
        }
        return mSensorPermissionApproved;
    }

    private static void setElevatedMarkerFalseIfItWasTrue() {
        if (PersistentStore.getBoolean(ELEVATED_MARKER)) {
            // last reading was elevated but this one isn't so clear the marker
            PersistentStore.setBoolean(ELEVATED_MARKER, false);
        }
    }

    public HeartRateService setInjectable() {
        attachBaseContext(xdrip.getAppContext());
        return this;
    }
}

18 Source : BeaconRadarFragment.java
with Apache License 2.0
from neXenio

public clreplaced BeaconRadarFragment extends BeaconViewFragment {

    private BeaconRadar beaconRadar;

    private SensorManager sensorManager;

    private SensorEventListener sensorEventListener;

    private final float[] accelerometerReading = new float[3];

    private final float[] magnetometerReading = new float[3];

    private final float[] rotationMatrix = new float[9];

    private final float[] orientationAngles = new float[3];

    public BeaconRadarFragment() {
        super();
        beaconFilters.add(uuidFilter);
        sensorEventListener = new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                switch(sensorEvent.sensor.getType()) {
                    case Sensor.TYPE_ACCELEROMETER:
                        {
                            System.arraycopy(sensorEvent.values, 0, accelerometerReading, 0, accelerometerReading.length);
                            break;
                        }
                    case Sensor.TYPE_MAGNETIC_FIELD:
                        {
                            System.arraycopy(sensorEvent.values, 0, magnetometerReading, 0, magnetometerReading.length);
                            break;
                        }
                }
                updateOrientationAngles();
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        };
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onDetach() {
        sensorManager.unregisterListener(sensorEventListener);
        super.onDetach();
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_beacon_radar;
    }

    @Override
    protected LocationListener createDeviceLocationListener() {
        return new LocationListener() {

            @Override
            public void onLocationUpdated(LocationProvider locationProvider, Location location) {
                if (locationProvider == IndoorPositioning.getInstance()) {
                    beaconRadar.setDeviceLocation(location);
                    beaconRadar.fitToCurrentLocations();
                }
            }
        };
    }

    @Override
    protected BeaconUpdateListener createBeaconUpdateListener() {
        return new BeaconUpdateListener() {

            @Override
            public void onBeaconUpdated(Beacon beacon) {
                beaconRadar.setBeacons(getBeacons());
            }
        };
    }

    @CallSuper
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflatedView = super.onCreateView(inflater, container, savedInstanceState);
        beaconRadar = inflatedView.findViewById(R.id.beaconRadar);
        beaconRadar.setBeacons(getBeacons());
        return inflatedView;
    }

    private void updateOrientationAngles() {
        SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerReading, magnetometerReading);
        SensorManager.getOrientation(rotationMatrix, orientationAngles);
        beaconRadar.startDeviceAngleAnimation((float) Math.toDegrees(orientationAngles[0]));
    }
}

18 Source : MainActivity.java
with MIT License
from murki

public clreplaced MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = MainActivity.clreplaced.getName();

    private Spinner bpModes;

    private SensorManager sensorManager;

    private RxSensorManager rxSensorManager;

    private Sensor accelerometer;

    private Subscription rxSensorSubscription;

    private Subscription rxSensorSubscriptionAsync;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bpModes = (Spinner) findViewById(R.id.bpModes);
        bpModes.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, AsyncEmitter.BackpressureMode.values()));
        setupSensorListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
    // TODO: Unregister existing listeners/subscriptions
    }

    public void registerSensor(View view) {
        Log.d(LOG_TAG, "registerSensor()");
        sensorManager.registerListener(sensorListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void unregisterSensor(View view) {
        Log.d(LOG_TAG, "unregisterSensor()");
        sensorManager.unregisterListener(sensorListener, accelerometer);
    }

    public void registerSensorRx(View view) {
        Log.d(LOG_TAG, "registerSensorRx()");
        rxSensorSubscription = rxSensorManager.naiveObserveSensorChanged(accelerometer, SensorManager.SENSOR_DELAY_FASTEST).observeOn(Schedulers.computation()).subscribe(sensorChangedOnNext, sensorChangedOnError);
    }

    public void unregisterSensorRx(View view) {
        Log.d(LOG_TAG, "unregisterSensorRx()");
        rxSensorSubscription.unsubscribe();
    }

    public void registerSensorRxAsync(View view) {
        Log.d(LOG_TAG, "registerSensorRxAsync()");
        rxSensorSubscriptionAsync = rxSensorManager.observeSensorChanged(accelerometer, SensorManager.SENSOR_DELAY_FASTEST, (AsyncEmitter.BackpressureMode) bpModes.getSelectedItem()).observeOn(Schedulers.computation()).subscribe(sensorChangedOnNext, sensorChangedOnError);
    }

    public void unregisterSensorRxAsync(View view) {
        Log.d(LOG_TAG, "unregisterSensorRxAsync()");
        rxSensorSubscriptionAsync.unsubscribe();
    }

    private void setupSensorListener() {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        rxSensorManager = new RxSensorManager(sensorManager);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    private final SensorEventListener sensorListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            try {
                // simulate a semi-expensive operation
                Thread.sleep(10);
            } catch (InterruptedException ignore) {
            }
            Log.d(LOG_TAG, "onSensorChanged() sensorEvent.timestamp=" + sensorEvent.timestamp + ", sensorEvent.values=" + Arrays.toString(sensorEvent.values));
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        // ignored for this example
        }
    };

    private final Action1<SensorEvent> sensorChangedOnNext = new Action1<SensorEvent>() {

        @Override
        public void call(SensorEvent sensorEvent) {
            try {
                // simulate a semi-expensive operation
                Thread.sleep(10);
            } catch (InterruptedException ignore) {
            }
            Log.d(LOG_TAG, "sensorChangedOnNext - sensorEvent.timestamp=" + sensorEvent.timestamp + ", sensorEvent.values=" + Arrays.toString(sensorEvent.values));
        }
    };

    private final Action1<Throwable> sensorChangedOnError = new Action1<Throwable>() {

        @Override
        public void call(Throwable throwable) {
            Log.e(LOG_TAG, "sensorChangedOnError", throwable);
        }
    };
}

18 Source : AutomaticBrightnessController.java
with Apache License 2.0
from lulululbj

clreplaced AutomaticBrightnessController {

    private static final String TAG = "AutomaticBrightnessController";

    private static final boolean DEBUG = false;

    private static final boolean DEBUG_PRETEND_LIGHT_SENSOR_ABSENT = false;

    // If true, enables the use of the screen auto-brightness adjustment setting.
    private static final boolean USE_SCREEN_AUTO_BRIGHTNESS_ADJUSTMENT = true;

    // How long the current sensor reading is replacedumed to be valid beyond the current time.
    // This provides a bit of prediction, as well as ensures that the weight for the last sample is
    // non-zero, which in turn ensures that the total weight is non-zero.
    private static final long AMBIENT_LIGHT_PREDICTION_TIME_MILLIS = 100;

    // Debounce for sampling user-initiated changes in display brightness to ensure
    // the user is satisfied with the result before storing the sample.
    private static final int BRIGHTNESS_ADJUSTMENT_SAMPLE_DEBOUNCE_MILLIS = 10000;

    // Timeout after which we remove the effects any user interactions might've had on the
    // brightness mapping. This timeout doesn't start until we transition to a non-interactive
    // display policy so that we don't reset while users are using their devices, but also so that
    // we don't erroneously keep the short-term model if the device is dozing but the display is
    // fully on.
    private static final int SHORT_TERM_MODEL_TIMEOUT_MILLIS = 30000;

    private static final int MSG_UPDATE_AMBIENT_LUX = 1;

    private static final int MSG_BRIGHTNESS_ADJUSTMENT_SAMPLE = 2;

    private static final int MSG_INVALIDATE_SHORT_TERM_MODEL = 3;

    // Length of the ambient light horizon used to calculate the long term estimate of ambient
    // light.
    private static final int AMBIENT_LIGHT_LONG_HORIZON_MILLIS = 10000;

    // Length of the ambient light horizon used to calculate short-term estimate of ambient light.
    private static final int AMBIENT_LIGHT_SHORT_HORIZON_MILLIS = 2000;

    // Callbacks for requesting updates to the display's power state
    private final Callbacks mCallbacks;

    // The sensor manager.
    private final SensorManager mSensorManager;

    // The light sensor, or null if not available or needed.
    private final Sensor mLightSensor;

    // The mapper to translate ambient lux to screen brightness in the range [0, 1.0].
    private final BrightnessMappingStrategy mBrightnessMapper;

    // The minimum and maximum screen brightnesses.
    private final int mScreenBrightnessRangeMinimum;

    private final int mScreenBrightnessRangeMaximum;

    // How much to scale doze brightness by (should be (0, 1.0]).
    private final float mDozeScaleFactor;

    // Initial light sensor event rate in milliseconds.
    private final int mInitialLightSensorRate;

    // Steady-state light sensor event rate in milliseconds.
    private final int mNormalLightSensorRate;

    // The current light sensor event rate in milliseconds.
    private int mCurrentLightSensorRate;

    // Stability requirements in milliseconds for accepting a new brightness level.  This is used
    // for debouncing the light sensor.  Different constants are used to debounce the light sensor
    // when adapting to brighter or darker environments.  This parameter controls how quickly
    // brightness changes occur in response to an observed change in light level that exceeds the
    // hysteresis threshold.
    private final long mBrighteningLightDebounceConfig;

    private final long mDarkeningLightDebounceConfig;

    // If true immediately after the screen is turned on the controller will try to adjust the
    // brightness based on the current sensor reads. If false, the controller will collect more data
    // and only then decide whether to change brightness.
    private final boolean mResetAmbientLuxAfterWarmUpConfig;

    // Period of time in which to consider light samples in milliseconds.
    private final int mAmbientLightHorizon;

    // The intercept used for the weighting calculation. This is used in order to keep all possible
    // weighting values positive.
    private final int mWeightingIntercept;

    // Configuration object for determining thresholds to change brightness dynamically
    private final HysteresisLevels mAmbientBrightnessThresholds;

    private final HysteresisLevels mScreenBrightnessThresholds;

    // Amount of time to delay auto-brightness after screen on while waiting for
    // the light sensor to warm-up in milliseconds.
    // May be 0 if no warm-up is required.
    private int mLightSensorWarmUpTimeConfig;

    // Set to true if the light sensor is enabled.
    private boolean mLightSensorEnabled;

    // The time when the light sensor was enabled.
    private long mLightSensorEnableTime;

    // The currently accepted nominal ambient light level.
    private float mAmbientLux;

    // True if mAmbientLux holds a valid value.
    private boolean mAmbientLuxValid;

    // The ambient light level threshold at which to brighten or darken the screen.
    private float mAmbientBrighteningThreshold;

    private float mAmbientDarkeningThreshold;

    // The screen light level threshold at which to brighten or darken the screen.
    private float mScreenBrighteningThreshold;

    private float mScreenDarkeningThreshold;

    // The most recent light sample.
    private float mLastObservedLux;

    // The time of the most light recent sample.
    private long mLastObservedLuxTime;

    // The number of light samples collected since the light sensor was enabled.
    private int mRecentLightSamples;

    // A ring buffer containing all of the recent ambient light sensor readings.
    private AmbientLightRingBuffer mAmbientLightRingBuffer;

    // The handler
    private AutomaticBrightnessHandler mHandler;

    // The screen brightness level that has been chosen by the auto-brightness
    // algorithm.  The actual brightness should ramp towards this value.
    // We preserve this value even when we stop using the light sensor so
    // that we can quickly revert to the previous auto-brightness level
    // while the light sensor warms up.
    // Use -1 if there is no current auto-brightness value available.
    private int mScreenAutoBrightness = -1;

    // The current display policy. This is useful, for example,  for knowing when we're dozing,
    // where the light sensor may not be available.
    private int mDisplayPolicy = DisplayPowerRequest.POLICY_OFF;

    // True if we are collecting a brightness adjustment sample, along with some data
    // for the initial state of the sample.
    private boolean mBrightnessAdjustmentSamplePending;

    private float mBrightnessAdjustmentSampleOldLux;

    private int mBrightnessAdjustmentSampleOldBrightness;

    // When the short term model is invalidated, we don't necessarily reset it (i.e. clear the
    // user's adjustment) immediately, but wait for a drastic enough change in the ambient light.
    // The anchor determines what were the light levels when the user has set her preference, and
    // we use a relative threshold to determine when to revert to the OEM curve.
    private boolean mShortTermModelValid;

    private float mShortTermModelAnchor;

    private float SHORT_TERM_MODEL_THRESHOLD_RATIO = 0.6f;

    public AutomaticBrightnessController(Callbacks callbacks, Looper looper, SensorManager sensorManager, BrightnessMappingStrategy mapper, int lightSensorWarmUpTime, int brightnessMin, int brightnessMax, float dozeScaleFactor, int lightSensorRate, int initialLightSensorRate, long brighteningLightDebounceConfig, long darkeningLightDebounceConfig, boolean resetAmbientLuxAfterWarmUpConfig, HysteresisLevels ambientBrightnessThresholds, HysteresisLevels screenBrightnessThresholds) {
        mCallbacks = callbacks;
        mSensorManager = sensorManager;
        mBrightnessMapper = mapper;
        mScreenBrightnessRangeMinimum = brightnessMin;
        mScreenBrightnessRangeMaximum = brightnessMax;
        mLightSensorWarmUpTimeConfig = lightSensorWarmUpTime;
        mDozeScaleFactor = dozeScaleFactor;
        mNormalLightSensorRate = lightSensorRate;
        mInitialLightSensorRate = initialLightSensorRate;
        mCurrentLightSensorRate = -1;
        mBrighteningLightDebounceConfig = brighteningLightDebounceConfig;
        mDarkeningLightDebounceConfig = darkeningLightDebounceConfig;
        mResetAmbientLuxAfterWarmUpConfig = resetAmbientLuxAfterWarmUpConfig;
        mAmbientLightHorizon = AMBIENT_LIGHT_LONG_HORIZON_MILLIS;
        mWeightingIntercept = AMBIENT_LIGHT_LONG_HORIZON_MILLIS;
        mAmbientBrightnessThresholds = ambientBrightnessThresholds;
        mScreenBrightnessThresholds = screenBrightnessThresholds;
        mShortTermModelValid = true;
        mShortTermModelAnchor = -1;
        mHandler = new AutomaticBrightnessHandler(looper);
        mAmbientLightRingBuffer = new AmbientLightRingBuffer(mNormalLightSensorRate, mAmbientLightHorizon);
        if (!DEBUG_PRETEND_LIGHT_SENSOR_ABSENT) {
            mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        }
    }

    public int getAutomaticScreenBrightness() {
        if (!mAmbientLuxValid) {
            return -1;
        }
        if (mDisplayPolicy == DisplayPowerRequest.POLICY_DOZE) {
            return (int) (mScreenAutoBrightness * mDozeScaleFactor);
        }
        return mScreenAutoBrightness;
    }

    public float getAutomaticScreenBrightnessAdjustment() {
        return mBrightnessMapper.getAutoBrightnessAdjustment();
    }

    public void configure(boolean enable, @Nullable BrightnessConfiguration configuration, float brightness, boolean userChangedBrightness, float adjustment, boolean userChangedAutoBrightnessAdjustment, int displayPolicy) {
        // While dozing, the application processor may be suspended which will prevent us from
        // receiving new information from the light sensor. On some devices, we may be able to
        // switch to a wake-up light sensor instead but for now we will simply disable the sensor
        // and hold onto the last computed screen auto brightness.  We save the dozing flag for
        // debugging purposes.
        boolean dozing = (displayPolicy == DisplayPowerRequest.POLICY_DOZE);
        boolean changed = setBrightnessConfiguration(configuration);
        changed |= setDisplayPolicy(displayPolicy);
        if (userChangedAutoBrightnessAdjustment) {
            changed |= setAutoBrightnessAdjustment(adjustment);
        }
        if (userChangedBrightness && enable) {
            // Update the brightness curve with the new user control point. It's critical this
            // happens after we update the autobrightness adjustment since it may reset it.
            changed |= setScreenBrightnessByUser(brightness);
        }
        final boolean userInitiatedChange = userChangedBrightness || userChangedAutoBrightnessAdjustment;
        if (userInitiatedChange && enable && !dozing) {
            prepareBrightnessAdjustmentSample();
        }
        changed |= setLightSensorEnabled(enable && !dozing);
        if (changed) {
            updateAutoBrightness(false);
        }
    }

    public boolean hasUserDataPoints() {
        return mBrightnessMapper.hasUserDataPoints();
    }

    public boolean isDefaultConfig() {
        return mBrightnessMapper.isDefaultConfig();
    }

    public BrightnessConfiguration getDefaultConfig() {
        return mBrightnessMapper.getDefaultConfig();
    }

    private boolean setDisplayPolicy(int policy) {
        if (mDisplayPolicy == policy) {
            return false;
        }
        final int oldPolicy = mDisplayPolicy;
        mDisplayPolicy = policy;
        if (DEBUG) {
            Slog.d(TAG, "Display policy transitioning from " + oldPolicy + " to " + policy);
        }
        if (!isInteractivePolicy(policy) && isInteractivePolicy(oldPolicy)) {
            mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_SHORT_TERM_MODEL, SHORT_TERM_MODEL_TIMEOUT_MILLIS);
        } else if (isInteractivePolicy(policy) && !isInteractivePolicy(oldPolicy)) {
            mHandler.removeMessages(MSG_INVALIDATE_SHORT_TERM_MODEL);
        }
        return true;
    }

    private static boolean isInteractivePolicy(int policy) {
        return policy == DisplayPowerRequest.POLICY_BRIGHT || policy == DisplayPowerRequest.POLICY_DIM || policy == DisplayPowerRequest.POLICY_VR;
    }

    private boolean setScreenBrightnessByUser(float brightness) {
        if (!mAmbientLuxValid) {
            // If we don't have a valid ambient lux then we don't have a valid brightness anyways,
            // and we can't use this data to add a new control point to the short-term model.
            return false;
        }
        mBrightnessMapper.addUserDataPoint(mAmbientLux, brightness);
        mShortTermModelValid = true;
        mShortTermModelAnchor = mAmbientLux;
        if (DEBUG) {
            Slog.d(TAG, "ShortTermModel: anchor=" + mShortTermModelAnchor);
        }
        return true;
    }

    public void resetShortTermModel() {
        mBrightnessMapper.clearUserDataPoints();
        mShortTermModelValid = true;
        mShortTermModelAnchor = -1;
    }

    private void invalidateShortTermModel() {
        if (DEBUG) {
            Slog.d(TAG, "ShortTermModel: invalidate user data");
        }
        mShortTermModelValid = false;
    }

    public boolean setBrightnessConfiguration(BrightnessConfiguration configuration) {
        if (mBrightnessMapper.setBrightnessConfiguration(configuration)) {
            resetShortTermModel();
            return true;
        }
        return false;
    }

    public void dump(PrintWriter pw) {
        pw.println();
        pw.println("Automatic Brightness Controller Configuration:");
        pw.println("  mScreenBrightnessRangeMinimum=" + mScreenBrightnessRangeMinimum);
        pw.println("  mScreenBrightnessRangeMaximum=" + mScreenBrightnessRangeMaximum);
        pw.println("  mDozeScaleFactor=" + mDozeScaleFactor);
        pw.println("  mInitialLightSensorRate=" + mInitialLightSensorRate);
        pw.println("  mNormalLightSensorRate=" + mNormalLightSensorRate);
        pw.println("  mLightSensorWarmUpTimeConfig=" + mLightSensorWarmUpTimeConfig);
        pw.println("  mBrighteningLightDebounceConfig=" + mBrighteningLightDebounceConfig);
        pw.println("  mDarkeningLightDebounceConfig=" + mDarkeningLightDebounceConfig);
        pw.println("  mResetAmbientLuxAfterWarmUpConfig=" + mResetAmbientLuxAfterWarmUpConfig);
        pw.println("  mAmbientLightHorizon=" + mAmbientLightHorizon);
        pw.println("  mWeightingIntercept=" + mWeightingIntercept);
        pw.println();
        pw.println("Automatic Brightness Controller State:");
        pw.println("  mLightSensor=" + mLightSensor);
        pw.println("  mLightSensorEnabled=" + mLightSensorEnabled);
        pw.println("  mLightSensorEnableTime=" + TimeUtils.formatUptime(mLightSensorEnableTime));
        pw.println("  mCurrentLightSensorRate=" + mCurrentLightSensorRate);
        pw.println("  mAmbientLux=" + mAmbientLux);
        pw.println("  mAmbientLuxValid=" + mAmbientLuxValid);
        pw.println("  mAmbientBrighteningThreshold=" + mAmbientBrighteningThreshold);
        pw.println("  mAmbientDarkeningThreshold=" + mAmbientDarkeningThreshold);
        pw.println("  mScreenBrighteningThreshold=" + mScreenBrighteningThreshold);
        pw.println("  mScreenDarkeningThreshold=" + mScreenDarkeningThreshold);
        pw.println("  mLastObservedLux=" + mLastObservedLux);
        pw.println("  mLastObservedLuxTime=" + TimeUtils.formatUptime(mLastObservedLuxTime));
        pw.println("  mRecentLightSamples=" + mRecentLightSamples);
        pw.println("  mAmbientLightRingBuffer=" + mAmbientLightRingBuffer);
        pw.println("  mScreenAutoBrightness=" + mScreenAutoBrightness);
        pw.println("  mDisplayPolicy=" + DisplayPowerRequest.policyToString(mDisplayPolicy));
        pw.println("  mShortTermModelAnchor=" + mShortTermModelAnchor);
        pw.println("  mShortTermModelValid=" + mShortTermModelValid);
        pw.println("  mBrightnessAdjustmentSamplePending=" + mBrightnessAdjustmentSamplePending);
        pw.println("  mBrightnessAdjustmentSampleOldLux=" + mBrightnessAdjustmentSampleOldLux);
        pw.println("  mBrightnessAdjustmentSampleOldBrightness=" + mBrightnessAdjustmentSampleOldBrightness);
        pw.println("  mShortTermModelValid=" + mShortTermModelValid);
        pw.println();
        mBrightnessMapper.dump(pw);
        pw.println();
        mAmbientBrightnessThresholds.dump(pw);
        mScreenBrightnessThresholds.dump(pw);
    }

    private boolean setLightSensorEnabled(boolean enable) {
        if (enable) {
            if (!mLightSensorEnabled) {
                mLightSensorEnabled = true;
                mLightSensorEnableTime = SystemClock.uptimeMillis();
                mCurrentLightSensorRate = mInitialLightSensorRate;
                mSensorManager.registerListener(mLightSensorListener, mLightSensor, mCurrentLightSensorRate * 1000, mHandler);
                return true;
            }
        } else if (mLightSensorEnabled) {
            mLightSensorEnabled = false;
            mAmbientLuxValid = !mResetAmbientLuxAfterWarmUpConfig;
            mRecentLightSamples = 0;
            mAmbientLightRingBuffer.clear();
            mCurrentLightSensorRate = -1;
            mHandler.removeMessages(MSG_UPDATE_AMBIENT_LUX);
            mSensorManager.unregisterListener(mLightSensorListener);
        }
        return false;
    }

    private void handleLightSensorEvent(long time, float lux) {
        Trace.traceCounter(Trace.TRACE_TAG_POWER, "ALS", (int) lux);
        mHandler.removeMessages(MSG_UPDATE_AMBIENT_LUX);
        if (mAmbientLightRingBuffer.size() == 0) {
            // switch to using the steady-state sample rate after grabbing the initial light sample
            adjustLightSensorRate(mNormalLightSensorRate);
        }
        applyLightSensorMeasurement(time, lux);
        updateAmbientLux(time);
    }

    private void applyLightSensorMeasurement(long time, float lux) {
        mRecentLightSamples++;
        mAmbientLightRingBuffer.prune(time - mAmbientLightHorizon);
        mAmbientLightRingBuffer.push(time, lux);
        // Remember this sample value.
        mLastObservedLux = lux;
        mLastObservedLuxTime = time;
    }

    private void adjustLightSensorRate(int lightSensorRate) {
        // if the light sensor rate changed, update the sensor listener
        if (lightSensorRate != mCurrentLightSensorRate) {
            if (DEBUG) {
                Slog.d(TAG, "adjustLightSensorRate: " + "previousRate=" + mCurrentLightSensorRate + ", " + "currentRate=" + lightSensorRate);
            }
            mCurrentLightSensorRate = lightSensorRate;
            mSensorManager.unregisterListener(mLightSensorListener);
            mSensorManager.registerListener(mLightSensorListener, mLightSensor, lightSensorRate * 1000, mHandler);
        }
    }

    private boolean setAutoBrightnessAdjustment(float adjustment) {
        return mBrightnessMapper.setAutoBrightnessAdjustment(adjustment);
    }

    private void setAmbientLux(float lux) {
        if (DEBUG) {
            Slog.d(TAG, "setAmbientLux(" + lux + ")");
        }
        if (lux < 0) {
            Slog.w(TAG, "Ambient lux was negative, ignoring and setting to 0");
            lux = 0;
        }
        mAmbientLux = lux;
        mAmbientBrighteningThreshold = mAmbientBrightnessThresholds.getBrighteningThreshold(lux);
        mAmbientDarkeningThreshold = mAmbientBrightnessThresholds.getDarkeningThreshold(lux);
        // If the short term model was invalidated and the change is drastic enough, reset it.
        if (!mShortTermModelValid && mShortTermModelAnchor != -1) {
            final float minAmbientLux = mShortTermModelAnchor - mShortTermModelAnchor * SHORT_TERM_MODEL_THRESHOLD_RATIO;
            final float maxAmbientLux = mShortTermModelAnchor + mShortTermModelAnchor * SHORT_TERM_MODEL_THRESHOLD_RATIO;
            if (minAmbientLux < mAmbientLux && mAmbientLux < maxAmbientLux) {
                if (DEBUG) {
                    Slog.d(TAG, "ShortTermModel: re-validate user data, ambient lux is " + minAmbientLux + " < " + mAmbientLux + " < " + maxAmbientLux);
                }
                mShortTermModelValid = true;
            } else {
                Slog.d(TAG, "ShortTermModel: reset data, ambient lux is " + mAmbientLux + "(" + minAmbientLux + ", " + maxAmbientLux + ")");
                resetShortTermModel();
            }
        }
    }

    private float calculateAmbientLux(long now, long horizon) {
        if (DEBUG) {
            Slog.d(TAG, "calculateAmbientLux(" + now + ", " + horizon + ")");
        }
        final int N = mAmbientLightRingBuffer.size();
        if (N == 0) {
            Slog.e(TAG, "calculateAmbientLux: No ambient light readings available");
            return -1;
        }
        // Find the first measurement that is just outside of the horizon.
        int endIndex = 0;
        final long horizonStartTime = now - horizon;
        for (int i = 0; i < N - 1; i++) {
            if (mAmbientLightRingBuffer.getTime(i + 1) <= horizonStartTime) {
                endIndex++;
            } else {
                break;
            }
        }
        if (DEBUG) {
            Slog.d(TAG, "calculateAmbientLux: selected endIndex=" + endIndex + ", point=(" + mAmbientLightRingBuffer.getTime(endIndex) + ", " + mAmbientLightRingBuffer.getLux(endIndex) + ")");
        }
        float sum = 0;
        float totalWeight = 0;
        long endTime = AMBIENT_LIGHT_PREDICTION_TIME_MILLIS;
        for (int i = N - 1; i >= endIndex; i--) {
            long eventTime = mAmbientLightRingBuffer.getTime(i);
            if (i == endIndex && eventTime < horizonStartTime) {
                // If we're at the final value, make sure we only consider the part of the sample
                // within our desired horizon.
                eventTime = horizonStartTime;
            }
            final long startTime = eventTime - now;
            float weight = calculateWeight(startTime, endTime);
            float lux = mAmbientLightRingBuffer.getLux(i);
            if (DEBUG) {
                Slog.d(TAG, "calculateAmbientLux: [" + startTime + ", " + endTime + "]: " + "lux=" + lux + ", " + "weight=" + weight);
            }
            totalWeight += weight;
            sum += lux * weight;
            endTime = startTime;
        }
        if (DEBUG) {
            Slog.d(TAG, "calculateAmbientLux: " + "totalWeight=" + totalWeight + ", " + "newAmbientLux=" + (sum / totalWeight));
        }
        return sum / totalWeight;
    }

    private float calculateWeight(long startDelta, long endDelta) {
        return weightIntegral(endDelta) - weightIntegral(startDelta);
    }

    // Evaluates the integral of y = x + mWeightingIntercept. This is always positive for the
    // horizon we're looking at and provides a non-linear weighting for light samples.
    private float weightIntegral(long x) {
        return x * (x * 0.5f + mWeightingIntercept);
    }

    private long nextAmbientLightBrighteningTransition(long time) {
        final int N = mAmbientLightRingBuffer.size();
        long earliestValidTime = time;
        for (int i = N - 1; i >= 0; i--) {
            if (mAmbientLightRingBuffer.getLux(i) <= mAmbientBrighteningThreshold) {
                break;
            }
            earliestValidTime = mAmbientLightRingBuffer.getTime(i);
        }
        return earliestValidTime + mBrighteningLightDebounceConfig;
    }

    private long nextAmbientLightDarkeningTransition(long time) {
        final int N = mAmbientLightRingBuffer.size();
        long earliestValidTime = time;
        for (int i = N - 1; i >= 0; i--) {
            if (mAmbientLightRingBuffer.getLux(i) >= mAmbientDarkeningThreshold) {
                break;
            }
            earliestValidTime = mAmbientLightRingBuffer.getTime(i);
        }
        return earliestValidTime + mDarkeningLightDebounceConfig;
    }

    private void updateAmbientLux() {
        long time = SystemClock.uptimeMillis();
        mAmbientLightRingBuffer.prune(time - mAmbientLightHorizon);
        updateAmbientLux(time);
    }

    private void updateAmbientLux(long time) {
        // If the light sensor was just turned on then immediately update our initial
        // estimate of the current ambient light level.
        if (!mAmbientLuxValid) {
            final long timeWhenSensorWarmedUp = mLightSensorWarmUpTimeConfig + mLightSensorEnableTime;
            if (time < timeWhenSensorWarmedUp) {
                if (DEBUG) {
                    Slog.d(TAG, "updateAmbientLux: Sensor not  ready yet: " + "time=" + time + ", " + "timeWhenSensorWarmedUp=" + timeWhenSensorWarmedUp);
                }
                mHandler.sendEmptyMessageAtTime(MSG_UPDATE_AMBIENT_LUX, timeWhenSensorWarmedUp);
                return;
            }
            setAmbientLux(calculateAmbientLux(time, AMBIENT_LIGHT_SHORT_HORIZON_MILLIS));
            mAmbientLuxValid = true;
            if (DEBUG) {
                Slog.d(TAG, "updateAmbientLux: Initializing: " + "mAmbientLightRingBuffer=" + mAmbientLightRingBuffer + ", " + "mAmbientLux=" + mAmbientLux);
            }
            updateAutoBrightness(true);
        }
        long nextBrightenTransition = nextAmbientLightBrighteningTransition(time);
        long nextDarkenTransition = nextAmbientLightDarkeningTransition(time);
        // Essentially, we calculate both a slow ambient lux, to ensure there's a true long-term
        // change in lighting conditions, and a fast ambient lux to determine what the new
        // brightness situation is since the slow lux can be quite slow to converge.
        // 
        // Note that both values need to be checked for sufficient change before updating the
        // proposed ambient light value since the slow value might be sufficiently far enough away
        // from the fast value to cause a recalculation while its actually just converging on
        // the fast value still.
        float slowAmbientLux = calculateAmbientLux(time, AMBIENT_LIGHT_LONG_HORIZON_MILLIS);
        float fastAmbientLux = calculateAmbientLux(time, AMBIENT_LIGHT_SHORT_HORIZON_MILLIS);
        if ((slowAmbientLux >= mAmbientBrighteningThreshold && fastAmbientLux >= mAmbientBrighteningThreshold && nextBrightenTransition <= time) || (slowAmbientLux <= mAmbientDarkeningThreshold && fastAmbientLux <= mAmbientDarkeningThreshold && nextDarkenTransition <= time)) {
            setAmbientLux(fastAmbientLux);
            if (DEBUG) {
                Slog.d(TAG, "updateAmbientLux: " + ((fastAmbientLux > mAmbientLux) ? "Brightened" : "Darkened") + ": " + "mAmbientBrighteningThreshold=" + mAmbientBrighteningThreshold + ", " + "mAmbientLightRingBuffer=" + mAmbientLightRingBuffer + ", " + "mAmbientLux=" + mAmbientLux);
            }
            updateAutoBrightness(true);
            nextBrightenTransition = nextAmbientLightBrighteningTransition(time);
            nextDarkenTransition = nextAmbientLightDarkeningTransition(time);
        }
        long nextTransitionTime = Math.min(nextDarkenTransition, nextBrightenTransition);
        // If one of the transitions is ready to occur, but the total weighted ambient lux doesn't
        // exceed the necessary threshold, then it's possible we'll get a transition time prior to
        // now. Rather than continually checking to see whether the weighted lux exceeds the
        // threshold, schedule an update for when we'd normally expect another light sample, which
        // should be enough time to decide whether we should actually transition to the new
        // weighted ambient lux or not.
        nextTransitionTime = nextTransitionTime > time ? nextTransitionTime : time + mNormalLightSensorRate;
        if (DEBUG) {
            Slog.d(TAG, "updateAmbientLux: Scheduling ambient lux update for " + nextTransitionTime + TimeUtils.formatUptime(nextTransitionTime));
        }
        mHandler.sendEmptyMessageAtTime(MSG_UPDATE_AMBIENT_LUX, nextTransitionTime);
    }

    private void updateAutoBrightness(boolean sendUpdate) {
        if (!mAmbientLuxValid) {
            return;
        }
        float value = mBrightnessMapper.getBrightness(mAmbientLux);
        int newScreenAutoBrightness = clampScreenBrightness(Math.round(value * PowerManager.BRIGHTNESS_ON));
        // If mScreenAutoBrightness is set, we should have screen{Brightening,Darkening}Threshold,
        // in which case we ignore the new screen brightness if it doesn't differ enough from the
        // previous one.
        if (mScreenAutoBrightness != -1 && newScreenAutoBrightness > mScreenDarkeningThreshold && newScreenAutoBrightness < mScreenBrighteningThreshold) {
            if (DEBUG) {
                Slog.d(TAG, "ignoring newScreenAutoBrightness: " + mScreenDarkeningThreshold + " < " + newScreenAutoBrightness + " < " + mScreenBrighteningThreshold);
            }
            return;
        }
        if (mScreenAutoBrightness != newScreenAutoBrightness) {
            if (DEBUG) {
                Slog.d(TAG, "updateAutoBrightness: " + "mScreenAutoBrightness=" + mScreenAutoBrightness + ", " + "newScreenAutoBrightness=" + newScreenAutoBrightness);
            }
            mScreenAutoBrightness = newScreenAutoBrightness;
            mScreenBrighteningThreshold = mScreenBrightnessThresholds.getBrighteningThreshold(newScreenAutoBrightness);
            mScreenDarkeningThreshold = mScreenBrightnessThresholds.getDarkeningThreshold(newScreenAutoBrightness);
            if (sendUpdate) {
                mCallbacks.updateBrightness();
            }
        }
    }

    private int clampScreenBrightness(int value) {
        return MathUtils.constrain(value, mScreenBrightnessRangeMinimum, mScreenBrightnessRangeMaximum);
    }

    private void prepareBrightnessAdjustmentSample() {
        if (!mBrightnessAdjustmentSamplePending) {
            mBrightnessAdjustmentSamplePending = true;
            mBrightnessAdjustmentSampleOldLux = mAmbientLuxValid ? mAmbientLux : -1;
            mBrightnessAdjustmentSampleOldBrightness = mScreenAutoBrightness;
        } else {
            mHandler.removeMessages(MSG_BRIGHTNESS_ADJUSTMENT_SAMPLE);
        }
        mHandler.sendEmptyMessageDelayed(MSG_BRIGHTNESS_ADJUSTMENT_SAMPLE, BRIGHTNESS_ADJUSTMENT_SAMPLE_DEBOUNCE_MILLIS);
    }

    private void cancelBrightnessAdjustmentSample() {
        if (mBrightnessAdjustmentSamplePending) {
            mBrightnessAdjustmentSamplePending = false;
            mHandler.removeMessages(MSG_BRIGHTNESS_ADJUSTMENT_SAMPLE);
        }
    }

    private void collectBrightnessAdjustmentSample() {
        if (mBrightnessAdjustmentSamplePending) {
            mBrightnessAdjustmentSamplePending = false;
            if (mAmbientLuxValid && mScreenAutoBrightness >= 0) {
                if (DEBUG) {
                    Slog.d(TAG, "Auto-brightness adjustment changed by user: " + "lux=" + mAmbientLux + ", " + "brightness=" + mScreenAutoBrightness + ", " + "ring=" + mAmbientLightRingBuffer);
                }
                EventLog.writeEvent(EventLogTags.AUTO_BRIGHTNESS_ADJ, mBrightnessAdjustmentSampleOldLux, mBrightnessAdjustmentSampleOldBrightness, mAmbientLux, mScreenAutoBrightness);
            }
        }
    }

    private final clreplaced AutomaticBrightnessHandler extends Handler {

        public AutomaticBrightnessHandler(Looper looper) {
            super(looper, null, true);
        }

        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case MSG_UPDATE_AMBIENT_LUX:
                    updateAmbientLux();
                    break;
                case MSG_BRIGHTNESS_ADJUSTMENT_SAMPLE:
                    collectBrightnessAdjustmentSample();
                    break;
                case MSG_INVALIDATE_SHORT_TERM_MODEL:
                    invalidateShortTermModel();
                    break;
            }
        }
    }

    private final SensorEventListener mLightSensorListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (mLightSensorEnabled) {
                final long time = SystemClock.uptimeMillis();
                final float lux = event.values[0];
                handleLightSensorEvent(time, lux);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Not used.
        }
    };

    /**
     * Callbacks to request updates to the display's power state.
     */
    interface Callbacks {

        void updateBrightness();
    }

    /**
     * A ring buffer of ambient light measurements sorted by time.
     *
     * Each entry consists of a timestamp and a lux measurement, and the overall buffer is sorted
     * from oldest to newest.
     */
    private static final clreplaced AmbientLightRingBuffer {

        // Proportional extra capacity of the buffer beyond the expected number of light samples
        // in the horizon
        private static final float BUFFER_SLACK = 1.5f;

        private float[] mRingLux;

        private long[] mRingTime;

        private int mCapacity;

        // The first valid element and the next open slot.
        // Note that if mCount is zero then there are no valid elements.
        private int mStart;

        private int mEnd;

        private int mCount;

        public AmbientLightRingBuffer(long lightSensorRate, int ambientLightHorizon) {
            mCapacity = (int) Math.ceil(ambientLightHorizon * BUFFER_SLACK / lightSensorRate);
            mRingLux = new float[mCapacity];
            mRingTime = new long[mCapacity];
        }

        public float getLux(int index) {
            return mRingLux[offsetOf(index)];
        }

        public long getTime(int index) {
            return mRingTime[offsetOf(index)];
        }

        public void push(long time, float lux) {
            int next = mEnd;
            if (mCount == mCapacity) {
                int newSize = mCapacity * 2;
                float[] newRingLux = new float[newSize];
                long[] newRingTime = new long[newSize];
                int length = mCapacity - mStart;
                System.arraycopy(mRingLux, mStart, newRingLux, 0, length);
                System.arraycopy(mRingTime, mStart, newRingTime, 0, length);
                if (mStart != 0) {
                    System.arraycopy(mRingLux, 0, newRingLux, length, mStart);
                    System.arraycopy(mRingTime, 0, newRingTime, length, mStart);
                }
                mRingLux = newRingLux;
                mRingTime = newRingTime;
                next = mCapacity;
                mCapacity = newSize;
                mStart = 0;
            }
            mRingTime[next] = time;
            mRingLux[next] = lux;
            mEnd = next + 1;
            if (mEnd == mCapacity) {
                mEnd = 0;
            }
            mCount++;
        }

        public void prune(long horizon) {
            if (mCount == 0) {
                return;
            }
            while (mCount > 1) {
                int next = mStart + 1;
                if (next >= mCapacity) {
                    next -= mCapacity;
                }
                if (mRingTime[next] > horizon) {
                    // Some light sensors only produce data upon a change in the ambient light
                    // levels, so we need to consider the previous measurement as the ambient light
                    // level for all points in time up until we receive a new measurement. Thus, we
                    // always want to keep the youngest element that would be removed from the
                    // buffer and just set its measurement time to the horizon time since at that
                    // point it is the ambient light level, and to remove it would be to drop a
                    // valid data point within our horizon.
                    break;
                }
                mStart = next;
                mCount -= 1;
            }
            if (mRingTime[mStart] < horizon) {
                mRingTime[mStart] = horizon;
            }
        }

        public int size() {
            return mCount;
        }

        public void clear() {
            mStart = 0;
            mEnd = 0;
            mCount = 0;
        }

        @Override
        public String toString() {
            StringBuffer buf = new StringBuffer();
            buf.append('[');
            for (int i = 0; i < mCount; i++) {
                final long next = i + 1 < mCount ? getTime(i + 1) : SystemClock.uptimeMillis();
                if (i != 0) {
                    buf.append(", ");
                }
                buf.append(getLux(i));
                buf.append(" / ");
                buf.append(next - getTime(i));
                buf.append("ms");
            }
            buf.append(']');
            return buf.toString();
        }

        private int offsetOf(int index) {
            if (index >= mCount || index < 0) {
                throw new ArrayIndexOutOfBoundsException(index);
            }
            index += mStart;
            if (index >= mCapacity) {
                index -= mCapacity;
            }
            return index;
        }
    }
}

18 Source : OrientationEventListener.java
with Apache License 2.0
from lulululbj

/**
 * Helper clreplaced for receiving notifications from the SensorManager when
 * the orientation of the device has changed.
 */
public abstract clreplaced OrientationEventListener {

    private static final String TAG = "OrientationEventListener";

    private static final boolean DEBUG = false;

    private static final boolean localLOGV = false;

    private int mOrientation = ORIENTATION_UNKNOWN;

    private SensorManager mSensorManager;

    private boolean mEnabled = false;

    private int mRate;

    private Sensor mSensor;

    private SensorEventListener mSensorEventListener;

    private OrientationListener mOldListener;

    /**
     * Returned from onOrientationChanged when the device orientation cannot be determined
     * (typically when the device is in a close to flat position).
     *
     *  @see #onOrientationChanged
     */
    public static final int ORIENTATION_UNKNOWN = -1;

    /**
     * Creates a new OrientationEventListener.
     *
     * @param context for the OrientationEventListener.
     */
    public OrientationEventListener(Context context) {
        this(context, SensorManager.SENSOR_DELAY_NORMAL);
    }

    /**
     * Creates a new OrientationEventListener.
     *
     * @param context for the OrientationEventListener.
     * @param rate at which sensor events are processed (see also
     * {@link android.hardware.SensorManager SensorManager}). Use the default
     * value of {@link android.hardware.SensorManager#SENSOR_DELAY_NORMAL
     * SENSOR_DELAY_NORMAL} for simple screen orientation change detection.
     */
    public OrientationEventListener(Context context, int rate) {
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        mRate = rate;
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (mSensor != null) {
            // Create listener only if sensors do exist
            mSensorEventListener = new SensorEventListenerImpl();
        }
    }

    void registerListener(OrientationListener lis) {
        mOldListener = lis;
    }

    /**
     * Enables the OrientationEventListener so it will monitor the sensor and call
     * {@link #onOrientationChanged} when the device orientation changes.
     */
    public void enable() {
        if (mSensor == null) {
            Log.w(TAG, "Cannot detect sensors. Not enabled");
            return;
        }
        if (mEnabled == false) {
            if (localLOGV)
                Log.d(TAG, "OrientationEventListener enabled");
            mSensorManager.registerListener(mSensorEventListener, mSensor, mRate);
            mEnabled = true;
        }
    }

    /**
     * Disables the OrientationEventListener.
     */
    public void disable() {
        if (mSensor == null) {
            Log.w(TAG, "Cannot detect sensors. Invalid disable");
            return;
        }
        if (mEnabled == true) {
            if (localLOGV)
                Log.d(TAG, "OrientationEventListener disabled");
            mSensorManager.unregisterListener(mSensorEventListener);
            mEnabled = false;
        }
    }

    clreplaced SensorEventListenerImpl implements SensorEventListener {

        private static final int _DATA_X = 0;

        private static final int _DATA_Y = 1;

        private static final int _DATA_Z = 2;

        public void onSensorChanged(SensorEvent event) {
            float[] values = event.values;
            int orientation = ORIENTATION_UNKNOWN;
            float X = -values[_DATA_X];
            float Y = -values[_DATA_Y];
            float Z = -values[_DATA_Z];
            float magnitude = X * X + Y * Y;
            // Don't trust the angle if the magnitude is small compared to the y value
            if (magnitude * 4 >= Z * Z) {
                float OneEightyOverPi = 57.29577957855f;
                float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
                orientation = 90 - (int) Math.round(angle);
                // normalize to 0 - 359 range
                while (orientation >= 360) {
                    orientation -= 360;
                }
                while (orientation < 0) {
                    orientation += 360;
                }
            }
            if (mOldListener != null) {
                mOldListener.onSensorChanged(Sensor.TYPE_ACCELEROMETER, event.values);
            }
            if (orientation != mOrientation) {
                mOrientation = orientation;
                onOrientationChanged(orientation);
            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    }

    /*
     * Returns true if sensor is enabled and false otherwise
     */
    public boolean canDetectOrientation() {
        return mSensor != null;
    }

    /**
     * Called when the orientation of the device has changed.
     * orientation parameter is in degrees, ranging from 0 to 359.
     * orientation is 0 degrees when the device is oriented in its natural position,
     * 90 degrees when its left side is at the top, 180 degrees when it is upside down,
     * and 270 degrees when its right side is to the top.
     * {@link #ORIENTATION_UNKNOWN} is returned when the device is close to flat
     * and the orientation cannot be determined.
     *
     * @param orientation The new orientation of the device.
     *
     *  @see #ORIENTATION_UNKNOWN
     */
    abstract public void onOrientationChanged(int orientation);
}

18 Source : SensorsTester.java
with Apache License 2.0
from JunhuaLin

/**
 * 执行权限操作接口<br/>
 * <p>
 * 参考:
 * https://github.com/yanzhenjie/AndPermission/tree/master/support/src/main/java/com/yanzhenjie/permission/checker
 *
 * @author junhua.lin<br />
 * CREATED 2019/6/6 10:37
 */
clreplaced SensorsTester implements PermissionTester {

    private Context mContext;

    SensorsTester(Context context) {
        this.mContext = context;
    }

    @Override
    public boolean test() throws Throwable {
        SensorManager sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        try {
            Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
            sensorManager.registerListener(SENSOR_EVENT_LISTENER, heartRateSensor, 3);
            sensorManager.unregisterListener(SENSOR_EVENT_LISTENER, heartRateSensor);
        } catch (Throwable e) {
            PackageManager packageManager = mContext.getPackageManager();
            return !packageManager.hreplacedystemFeature(PackageManager.FEATURE_SENSOR_HEART_RATE);
        }
        return true;
    }

    private static final SensorEventListener SENSOR_EVENT_LISTENER = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
        }

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

18 Source : PermissionsChecker.java
with Apache License 2.0
from jokermonn

/**
 * use sensors, {@link android.Manifest.permission#BODY_SENSORS}
 *
 * @param activity
 * @return true if success
 * @throws Exception
 */
private static boolean checkBodySensors(Activity activity) throws Exception {
    SensorManager sensorManager = (SensorManager) activity.getSystemService(SENSOR_SERVICE);
    Sensor sensor = sensorManager.getDefaultSensor((Sensor.TYPE_ACCELEROMETER));
    SensorEventListener listener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
    sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);
    sensorManager.unregisterListener(listener, sensor);
    return true;
}

18 Source : SensorTest.java
with Apache License 2.0
from jiyouliang

public clreplaced SensorTest extends GraphicsActivity {

    private final String TAG = "SensorTest";

    private SensorManager mSensorManager;

    private Sensor mSensor;

    private SampleView mView;

    private float[] mValues;

    private static clreplaced RunAve {

        private final float[] mWeights;

        private final float mWeightScale;

        private final float[] mSamples;

        private final int mDepth;

        private int mCurr;

        public RunAve(float[] weights) {
            mWeights = weights;
            float sum = 0;
            for (int i = 0; i < weights.length; i++) {
                sum += weights[i];
            }
            mWeightScale = 1 / sum;
            mDepth = weights.length;
            mSamples = new float[mDepth];
            mCurr = 0;
        }

        public void addSample(float value) {
            mSamples[mCurr] = value;
            mCurr = (mCurr + 1) % mDepth;
        }

        public float computeAve() {
            final int depth = mDepth;
            int index = mCurr;
            float sum = 0;
            for (int i = 0; i < depth; i++) {
                sum += mWeights[i] * mSamples[index];
                index -= 1;
                if (index < 0) {
                    index = depth - 1;
                }
            }
            return sum * mWeightScale;
        }
    }

    private final SensorEventListener mListener = new SensorEventListener() {

        // accel
        private final float[] mScale = new float[] { 2, 2.5f, 0.5f };

        private float[] mPrev = new float[3];

        private long mLastGestureTime;

        public void onSensorChanged(SensorEvent event) {
            boolean show = false;
            float[] diff = new float[3];
            for (int i = 0; i < 3; i++) {
                diff[i] = Math.round(mScale[i] * (event.values[i] - mPrev[i]) * 0.45f);
                if (Math.abs(diff[i]) > 0) {
                    show = true;
                }
                mPrev[i] = event.values[i];
            }
            if (show) {
                // only shows if we think the delta is big enough, in an attempt
                // to detect "serious" moves left/right or up/down
                Log.e(TAG, "sensorChanged " + event.sensor.getName() + " (" + event.values[0] + ", " + event.values[1] + ", " + event.values[2] + ")" + " diff(" + diff[0] + " " + diff[1] + " " + diff[2] + ")");
            }
            long now = android.os.SystemClock.uptimeMillis();
            if (now - mLastGestureTime > 1000) {
                mLastGestureTime = 0;
                float x = diff[0];
                float y = diff[1];
                boolean gestX = Math.abs(x) > 3;
                boolean gestY = Math.abs(y) > 3;
                if ((gestX || gestY) && !(gestX && gestY)) {
                    if (gestX) {
                        if (x < 0) {
                            Log.e("test", "<<<<<<<< LEFT <<<<<<<<<<<<");
                        } else {
                            Log.e("test", ">>>>>>>>> RITE >>>>>>>>>>>");
                        }
                    } else {
                        if (y < -2) {
                            Log.e("test", "<<<<<<<< UP <<<<<<<<<<<<");
                        } else {
                            Log.e("test", ">>>>>>>>> DOWN >>>>>>>>>>>");
                        }
                    }
                    mLastGestureTime = now;
                }
            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mView = new SampleView(this);
        setContentView(mView);
        if (false)
            Log.d(TAG, "create " + mSensorManager);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
        if (false)
            Log.d(TAG, "resume " + mSensorManager);
    }

    @Override
    protected void onStop() {
        mSensorManager.unregisterListener(mListener);
        super.onStop();
        if (false)
            Log.d(TAG, "stop " + mSensorManager);
    }

    private clreplaced SampleView extends View {

        private Paint mPaint = new Paint();

        private Path mPath = new Path();

        private boolean mAnimate;

        public SampleView(Context context) {
            super(context);
            // Construct a wedge-shaped path
            mPath.moveTo(0, -50);
            mPath.lineTo(-20, 60);
            mPath.lineTo(0, 50);
            mPath.lineTo(20, 60);
            mPath.close();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = mPaint;
            canvas.drawColor(Color.WHITE);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);
            int w = canvas.getWidth();
            int h = canvas.getHeight();
            int cx = w / 2;
            int cy = h / 2;
            canvas.translate(cx, cy);
            if (mValues != null) {
                canvas.rotate(-mValues[0]);
            }
            canvas.drawPath(mPath, mPaint);
        }

        @Override
        protected void onAttachedToWindow() {
            mAnimate = true;
            if (false)
                Log.d(TAG, "onAttachedToWindow. mAnimate=" + mAnimate);
            super.onAttachedToWindow();
        }

        @Override
        protected void onDetachedFromWindow() {
            mAnimate = false;
            if (false)
                Log.d(TAG, "onAttachedToWindow. mAnimate=" + mAnimate);
            super.onDetachedFromWindow();
        }
    }
}

18 Source : Compass.java
with Apache License 2.0
from jiyouliang

public clreplaced Compreplaced extends GraphicsActivity {

    private static final String TAG = "Compreplaced";

    private SensorManager mSensorManager;

    private Sensor mSensor;

    private SampleView mView;

    private float[] mValues;

    private final SensorEventListener mListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent event) {
            if (false)
                Log.d(TAG, "sensorChanged (" + event.values[0] + ", " + event.values[1] + ", " + event.values[2] + ")");
            mValues = event.values;
            if (mView != null) {
                mView.invalidate();
            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        mView = new SampleView(this);
        setContentView(mView);
    }

    @Override
    protected void onResume() {
        if (false)
            Log.d(TAG, "onResume");
        super.onResume();
        mSensorManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onStop() {
        if (false)
            Log.d(TAG, "onStop");
        mSensorManager.unregisterListener(mListener);
        super.onStop();
    }

    private clreplaced SampleView extends View {

        private Paint mPaint = new Paint();

        private Path mPath = new Path();

        private boolean mAnimate;

        public SampleView(Context context) {
            super(context);
            // Construct a wedge-shaped path
            mPath.moveTo(0, -50);
            mPath.lineTo(-20, 60);
            mPath.lineTo(0, 50);
            mPath.lineTo(20, 60);
            mPath.close();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = mPaint;
            canvas.drawColor(Color.WHITE);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);
            int w = canvas.getWidth();
            int h = canvas.getHeight();
            int cx = w / 2;
            int cy = h / 2;
            canvas.translate(cx, cy);
            if (mValues != null) {
                canvas.rotate(-mValues[0]);
            }
            canvas.drawPath(mPath, mPaint);
        }

        @Override
        protected void onAttachedToWindow() {
            mAnimate = true;
            if (false)
                Log.d(TAG, "onAttachedToWindow. mAnimate=" + mAnimate);
            super.onAttachedToWindow();
        }

        @Override
        protected void onDetachedFromWindow() {
            mAnimate = false;
            if (false)
                Log.d(TAG, "onDetachedFromWindow. mAnimate=" + mAnimate);
            super.onDetachedFromWindow();
        }
    }
}

18 Source : SensorMetricsCollectorTest.java
with MIT License
from facebookincubator

/**
 * <pre>
 * Time                = 01 .. 10 .. 15 .. 20 .. 50
 * Sensor A/Listener A = [............]
 * Sensor B/Listener B =       [............]
 * </pre>
 */
@Test
public void test_multiple_listeners_sensors() {
    Sensor sensorB = mock(Sensor.clreplaced);
    SensorEventListener listenerB = mock(SensorEventListener.clreplaced);
    ShadowSystemClock.setElapsedRealtime(1);
    collector.register(listener, sensor);
    ShadowSystemClock.setElapsedRealtime(5);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(4);
    ShadowSystemClock.setElapsedRealtime(10);
    collector.register(listenerB, sensorB);
    ShadowSystemClock.setElapsedRealtime(13);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(12 + 3);
    ShadowSystemClock.setElapsedRealtime(15);
    collector.unregister(listener, null);
    ShadowSystemClock.setElapsedRealtime(18);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(14 + 8);
    ShadowSystemClock.setElapsedRealtime(20);
    collector.unregister(listenerB, null);
    ShadowSystemClock.setElapsedRealtime(50);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(14 + 10);
}

18 Source : SensorMetricsCollectorTest.java
with MIT License
from facebookincubator

/**
 * <pre>
 * Time               = 01 .. 10 .. 15 .. 20 .. 25
 * Sensor/Listener A  = [..................]
 * Sensor/Listener B  =       [......]
 * </pre>
 */
@Test
public void test_multiple_listeners_single_sensor() {
    SensorEventListener listenerB = mock(SensorEventListener.clreplaced);
    ShadowSystemClock.setElapsedRealtime(1);
    collector.register(listener, sensor);
    ShadowSystemClock.setElapsedRealtime(5);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(4);
    ShadowSystemClock.setElapsedRealtime(10);
    collector.register(listenerB, sensor);
    ShadowSystemClock.setElapsedRealtime(11);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(10);
    ShadowSystemClock.setElapsedRealtime(15);
    collector.unregister(listenerB, null);
    ShadowSystemClock.setElapsedRealtime(20);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(19);
    collector.unregister(listener, null);
    ShadowSystemClock.setElapsedRealtime(25);
    replacedertThat(collector.getSnapshot(metrics)).isTrue();
    replacedertThat(metrics.total.activeTimeMs).isEqualTo(19);
}

18 Source : Gyro.java
with GNU General Public License v3.0
from eszdman

public clreplaced Gyro {

    private static final String TAG = "Gyroscope";

    protected final float fk = 0.8f;

    private final SensorManager mSensorManager;

    private final Sensor mGyroSensor;

    public float[] mAngles;

    private boolean gyroburst = false;

    private float burstout = 0.f;

    private int filter = -1;

    private final SensorEventListener mGravityTracker = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            mAngles = sensorEvent.values;
            if (gyroburst) {
                for (float f : mAngles) {
                    burstout += Math.abs((f));
                }
            } else
                // For filtering
                getShakiness();
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };

    public Gyro(SensorManager sensorManager) {
        mSensorManager = sensorManager;
        mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    }

    public void register() {
        mSensorManager.registerListener(mGravityTracker, mGyroSensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    public void unregister() {
        if (mAngles != null)
            mAngles = mAngles.clone();
        mSensorManager.unregisterListener(mGravityTracker, mGyroSensor);
    }

    public void CaptureGyroBurst() {
        burstout = 0;
        gyroburst = true;
    }

    public float CompleteGyroBurst() {
        gyroburst = false;
        return Math.min(burstout * burstout, Float.MAX_VALUE);
    }

    public int getShakiness() {
        if (mAngles == null) {
            return 0;
        }
        int output = 0;
        for (float f : mAngles) {
            output += Math.abs((int) (f * 1000));
        }
        if (filter == -1) {
            filter = output;
        }
        output = (int) (output * (1.0f - fk) + filter * (fk));
        filter = output;
        return output;
    }
}

18 Source : Gravity.java
with GNU General Public License v3.0
from eszdman

public clreplaced Gravity {

    private static final String TAG = "Gravity";

    private final SensorManager mSensorManager;

    private final Sensor mGravitySensor;

    public float[] mGravity;

    private final SensorEventListener mGravityTracker = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            mGravity = sensorEvent.values;
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };

    public Gravity(SensorManager sensorManager) {
        mSensorManager = sensorManager;
        mGravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
    }

    public void register() {
        mSensorManager.registerListener(mGravityTracker, mGravitySensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    public void unregister() {
        if (mGravity != null)
            mGravity = mGravity.clone();
        mSensorManager.unregisterListener(mGravityTracker, mGravitySensor);
    }

    public int getRotation() {
        if (mGravity == null) {
            return 90;
        }
        if (// pointing at the ground
        mGravity[2] > 9f)
            return 90;
        if (Math.abs(mGravity[0]) > Math.abs(mGravity[1])) {
            if (mGravity[0] > 0f)
                return 0;
            else
                return 180;
        } else {
            if (mGravity[1] > 1.5f)
                return 90;
            else
                return 270;
        }
    }

    public int getCameraRotation(int sensorOrientation) {
        return (sensorOrientation + getRotation() + 270) % 360;
    }
}

18 Source : ShakeDetector.java
with Apache License 2.0
from aws-amplify

/**
 * Detects a device shake event.
 */
public final clreplaced ShakeDetector {

    // A device movement is clreplacedified as a shake if the acceleration
    // is above this threshold.
    private static final double SHAKE_THRESHOLD = SensorManager.GRAVITY_EARTH * 1.33f;

    // The minimum duration (in milliseconds) that the device needs to
    // be shaken in order to make the developer menu appear or disappear.
    private static final int SHAKE_TIME = 1000;

    // Listener to handle shake events.
    private final ShakeDetector.Listener listener;

    // Manager for the device's sensors.
    private SensorManager sensorManager;

    // The accelerometer sensor replacedociated with the device.
    private Sensor accelerometer;

    // The time (in milliseconds) that the device started shaking
    // (or 0 if the device is not shaking).
    private long shakeStart;

    // Listen to accelerometer sensor events.
    private final SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            // acceleration in the x-direction
            float xAccel = sensorEvent.values[0];
            // acceleration in the y-direction
            float yAccel = sensorEvent.values[1];
            // acceleration in the z-direction
            float zAccel = sensorEvent.values[2];
            double curAcceleration = Math.sqrt(((xAccel * xAccel) + (yAccel * yAccel) + (zAccel * zAccel)));
            if (curAcceleration > SHAKE_THRESHOLD) {
                long currentTime = Time.now();
                if (shakeStart == 0) {
                    shakeStart = currentTime;
                } else if (currentTime - shakeStart > SHAKE_TIME) {
                    listener.onShakeDetected();
                    shakeStart = 0;
                }
            }
        }

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

    /**
     * Gain access to the accelerometer sensor.
     * @param context An Android Context
     * @param listener ShakeDetector.Listener object
     */
    public ShakeDetector(Context context, ShakeDetector.Listener listener) {
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            accelerometer = this.sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        this.listener = listener;
        shakeStart = 0;
    }

    /**
     * Start listening to the accelerometer sensor for a shake event.
     */
    public void startDetecting() {
        if (accelerometer != null) {
            sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    /**
     * Stop listening to the accelerometer sensor for a shake event.
     */
    public void stopDetecting() {
        if (accelerometer != null) {
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    /**
     * Interface to handle shake events when they occur.
     */
    public interface Listener {

        /**
         * Called when a shake event is detected.
         */
        void onShakeDetected();
    }
}

18 Source : AmbientLightSensor.java
with Apache License 2.0
from arduino

/**
 * Clreplaced to get sensor data from the Ambient Light sensor. This uses a DataRefresher to send the
 * data to deal with low frequency of SensorEvent. This sensor does not send onSensorChanged events
 * very frequently, leading to the graph being updated infrequently and then jumping when it does
 * get an update without a refresher.
 */
public clreplaced AmbientLightSensor extends ScalarSensor {

    public static final String ID = "AmbientLightSensor";

    private final SystemScheduler scheduler = new SystemScheduler();

    private SensorEventListener sensorEventListener;

    private DataRefresher dataRefresher;

    public AmbientLightSensor() {
        super(ID);
    }

    @Override
    protected SensorRecorder makeScalarControl(final StreamConsumer c, final SensorEnvironment environment, final Context context, final SensorStatusListener listener) {
        return new AbstractSensorRecorder() {

            @Override
            public void startObserving() {
                dataRefresher = new DataRefresher(scheduler, environment.getDefaultClock());
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_CONNECTED);
                SensorManager sensorManager = getSensorManager(context);
                Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
                if (sensorEventListener != null) {
                    getSensorManager(context).unregisterListener(sensorEventListener);
                }
                sensorEventListener = new SensorEventListener() {

                    @Override
                    public void onSensorChanged(SensorEvent event) {
                        // values[0] is the ambient light level in SI lux units.
                        dataRefresher.setValue(event.values[0]);
                        dataRefresher.startStreaming();
                    }

                    @Override
                    public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    }
                };
                sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_UI);
                dataRefresher.setStreamConsumer(c);
            }

            @Override
            public void stopObserving() {
                getSensorManager(context).unregisterListener(sensorEventListener);
                listener.onSourceStatus(getId(), SensorStatusListener.STATUS_DISCONNECTED);
                if (dataRefresher != null) {
                    dataRefresher.stopStreaming();
                    dataRefresher = null;
                }
            }

            @Override
            public void applyOptions(ReadableSensorOptions settings) {
            // do nothing, no settings apply to collection
            }
        };
    }

    public static boolean isAmbientLightAvailable(AvailableSensors availableSensors) {
        return availableSensors.isSensorAvailable(Sensor.TYPE_LIGHT);
    }
}

18 Source : CheckSharedValues.java
with Apache License 2.0
from androidx

public clreplaced CheckSharedValues extends AppCompatActivity {

    private static final String TAG = "CheckSharedValues";

    // Demo00vt.clreplaced};
    Clreplaced[] demos = {};

    String layout_name;

    private SensorManager sensorManager;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extra = getIntent().getExtras();
        String prelayout = extra.getString(Utils.KEY);
        layout_name = prelayout;
        Context ctx = getApplicationContext();
        int id = ctx.getResources().getIdentifier(prelayout, "layout", ctx.getPackageName());
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.hide();
        }
        setContentView(id);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        Sensor sensor2 = sensorManager.getDefaultSensor(Sensor.TYPE_HINGE_ANGLE);
        Log.v(TAG, Debug.getLoc());
        MotionLayout ml = Utils.findMotionLayout(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            sensorManager.registerListener(gravity_listener, sensor, 100000);
            sensorManager.registerListener(angle_listener, sensor2, 100000);
        }
    }

    SensorEventListener gravity_listener = new SensorEventListener() {

        boolean lastState = false;

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            boolean state = sensorEvent.values[2] > 8;
            if (state == lastState) {
                return;
            }
            lastState = state;
            Log.v(TAG, Debug.getLoc() + " Acceleration = " + Arrays.toString(sensorEvent.values));
            ConstraintLayout.getSharedValues().fireNewValue(R.id.layFlat, state ? 1 : 0);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };

    SensorEventListener angle_listener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            Log.v(TAG, Debug.getLoc() + " Angle = " + Arrays.toString(sensorEvent.values));
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(gravity_listener);
    }
}

18 Source : BatchStepSensorFragment.java
with Apache License 2.0
from android

public clreplaced BatchStepSensorFragment extends Fragment implements OnCardClickListener {

    public static final String TAG = "StepSensorSample";

    // Cards
    private CardStreamFragment mCards = null;

    // Card tags
    public static final String CARD_INTRO = "intro";

    public static final String CARD_REGISTER_DETECTOR = "register_detector";

    public static final String CARD_REGISTER_COUNTER = "register_counter";

    public static final String CARD_BATCHING_DESCRIPTION = "register_batching_description";

    public static final String CARD_COUNTING = "counting";

    public static final String CARD_EXPLANATION = "explanation";

    public static final String CARD_NOBATCHSUPPORT = "error";

    // Actions from REGISTER cards
    public static final int ACTION_REGISTER_DETECT_NOBATCHING = 10;

    public static final int ACTION_REGISTER_DETECT_BATCHING_5s = 11;

    public static final int ACTION_REGISTER_DETECT_BATCHING_10s = 12;

    public static final int ACTION_REGISTER_COUNT_NOBATCHING = 21;

    public static final int ACTION_REGISTER_COUNT_BATCHING_5s = 22;

    public static final int ACTION_REGISTER_COUNT_BATCHING_10s = 23;

    // Action from COUNTING card
    public static final int ACTION_UNREGISTER = 1;

    // Actions from description cards
    private static final int ACTION_BATCHING_DESCRIPTION_DISMISS = 2;

    private static final int ACTION_EXPLANATION_DISMISS = 3;

    // State of application, used to register for sensors when app is restored
    public static final int STATE_OTHER = 0;

    public static final int STATE_COUNTER = 1;

    public static final int STATE_DETECTOR = 2;

    // Bundle tags used to store data when restoring application state
    private static final String BUNDLE_STATE = "state";

    private static final String BUNDLE_LATENCY = "latency";

    private static final String BUNDLE_STEPS = "steps";

    // max batch latency is specified in microseconds
    // no batching
    private static final int BATCH_LATENCY_0 = 0;

    private static final int BATCH_LATENCY_10s = 10000000;

    private static final int BATCH_LATENCY_5s = 5000000;

    /*
    For illustration we keep track of the last few events and show their delay from when the
    event occurred until it was received by the event listener.
    These variables keep track of the list of timestamps and the number of events.
     */
    // Number of events to keep in queue and display on card
    private static final int EVENT_QUEUE_LENGTH = 10;

    // List of timestamps when sensor events occurred
    private float[] mEventDelays = new float[EVENT_QUEUE_LENGTH];

    // number of events in event list
    private int mEventLength = 0;

    // pointer to next entry in sensor event list
    private int mEventData = 0;

    // Steps counted in current session
    private int mSteps = 0;

    // Value of the step counter sensor when the listener was registered.
    // (Total steps are calculated from this value.)
    private int mCounterSteps = 0;

    // Steps counted by the step counter previously. Used to keep counter consistent across rotation
    // changes
    private int mPreviousCounterSteps = 0;

    // State of the app (STATE_OTHER, STATE_COUNTER or STATE_DETECTOR)
    private int mState = STATE_OTHER;

    // When a listener is registered, the batch sensor delay in microseconds
    private int mMaxDelay = 0;

    @Override
    public void onResume() {
        super.onResume();
        CardStreamFragment stream = getCardStream();
        if (stream.getVisibleCardCount() < 1) {
            // No cards are visible, started for the first time
            // Prepare all cards and show the intro card.
            initialiseCards();
            showIntroCard();
            // Show the registration card if the hardware is supported, show an error otherwise
            if (isKitkatWithStepSensor()) {
                showRegisterCard();
            } else {
                showErrorCard();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // BEGIN_INCLUDE(onpause)
        // Unregister the listener when the application is paused
        unregisterListeners();
    // END_INCLUDE(onpause)
    }

    /**
     * Returns true if this device is supported. It needs to be running Android KitKat (4.4) or
     * higher and has a step counter and step detector sensor.
     * This check is useful when an app provides an alternative implementation or different
     * functionality if the step sensors are not available or this code runs on a platform version
     * below Android KitKat. If this functionality is required, then the minSDK parameter should
     * be specified appropriately in the AndroidManifest.
     *
     * @return True iff the device can run this sample
     */
    private boolean isKitkatWithStepSensor() {
        // BEGIN_INCLUDE(iskitkatsensor)
        // Require at least Android KitKat
        int currentApiVersion = android.os.Build.VERSION.SDK_INT;
        // Check that the device supports the step counter and detector sensors
        PackageManager packageManager = getActivity().getPackageManager();
        return currentApiVersion >= android.os.Build.VERSION_CODES.KITKAT && packageManager.hreplacedystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER) && packageManager.hreplacedystemFeature(PackageManager.FEATURE_SENSOR_STEP_DETECTOR);
    // END_INCLUDE(iskitkatsensor)
    }

    /**
     * Handles a click on a card action.
     * Registers a SensorEventListener (see {@link #registerEventListener(int, int)}) with the
     * selected delay, dismisses cards and unregisters the listener
     * (see {@link #unregisterListeners()}).
     * Actions are defined when a card is created.
     *
     * @param cardActionId
     * @param cardTag
     */
    @Override
    public void onCardClick(int cardActionId, String cardTag) {
        switch(cardActionId) {
            // BEGIN_INCLUDE(onclick)
            // Register Step Counter card
            case ACTION_REGISTER_COUNT_NOBATCHING:
                registerEventListener(BATCH_LATENCY_0, Sensor.TYPE_STEP_COUNTER);
                break;
            case ACTION_REGISTER_COUNT_BATCHING_5s:
                registerEventListener(BATCH_LATENCY_5s, Sensor.TYPE_STEP_COUNTER);
                break;
            case ACTION_REGISTER_COUNT_BATCHING_10s:
                registerEventListener(BATCH_LATENCY_10s, Sensor.TYPE_STEP_COUNTER);
                break;
            // Register Step Detector card
            case ACTION_REGISTER_DETECT_NOBATCHING:
                registerEventListener(BATCH_LATENCY_0, Sensor.TYPE_STEP_DETECTOR);
                break;
            case ACTION_REGISTER_DETECT_BATCHING_5s:
                registerEventListener(BATCH_LATENCY_5s, Sensor.TYPE_STEP_DETECTOR);
                break;
            case ACTION_REGISTER_DETECT_BATCHING_10s:
                registerEventListener(BATCH_LATENCY_10s, Sensor.TYPE_STEP_DETECTOR);
                break;
            // Unregister card
            case ACTION_UNREGISTER:
                showRegisterCard();
                unregisterListeners();
                // reset the application state when explicitly unregistered
                mState = STATE_OTHER;
                break;
            // END_INCLUDE(onclick)
            // Explanation cards
            case ACTION_BATCHING_DESCRIPTION_DISMISS:
                // permanently remove the batch description card, it will not be shown again
                getCardStream().removeCard(CARD_BATCHING_DESCRIPTION);
                break;
            case ACTION_EXPLANATION_DISMISS:
                // permanently remove the explanation card, it will not be shown again
                getCardStream().removeCard(CARD_EXPLANATION);
        }
        // For register cards, display the counting card
        if (cardTag.equals(CARD_REGISTER_COUNTER) || cardTag.equals(CARD_REGISTER_DETECTOR)) {
            showCountingCards();
        }
    }

    /**
     * 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)
    }

    /**
     * Unregisters the sensor listener if it is registered.
     */
    private void unregisterListeners() {
        // BEGIN_INCLUDE(unregister)
        SensorManager sensorManager = (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
        sensorManager.unregisterListener(mListener);
        Log.i(TAG, "Sensor listener unregistered.");
    // END_INCLUDE(unregister)
    }

    /**
     * Resets the step counter by clearing all counting variables and lists.
     */
    private void resetCounter() {
        // BEGIN_INCLUDE(reset)
        mSteps = 0;
        mCounterSteps = 0;
        mEventLength = 0;
        mEventDelays = new float[EVENT_QUEUE_LENGTH];
        mPreviousCounterSteps = 0;
    // END_INCLUDE(reset)
    }

    /**
     * Listener that handles step sensor events for step detector and step counter sensors.
     */
    private final SensorEventListener mListener = new SensorEventListener() {

        @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).setreplacedle(getString(R.string.counting_replacedle, 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).setreplacedle(getString(R.string.counting_replacedle, 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)
            }
        }

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

    /**
     * Records the delay for the event.
     *
     * @param event
     */
    private void recordDelay(SensorEvent event) {
        // Calculate the delay from when event was recorded until it was received here in ms
        // Event timestamp is recorded in us accuracy, but ms accuracy is sufficient here
        mEventDelays[mEventData] = System.currentTimeMillis() - (event.timestamp / 1000000L);
        // Increment length counter
        mEventLength = Math.min(EVENT_QUEUE_LENGTH, mEventLength + 1);
        // Move pointer to the next (oldest) location
        mEventData = (mEventData + 1) % EVENT_QUEUE_LENGTH;
    }

    private final StringBuffer mDelayStringBuffer = new StringBuffer();

    /**
     * Returns a string describing the sensor delays recorded in
     * {@link #recordDelay(android.hardware.SensorEvent)}.
     *
     * @return
     */
    private String getDelayString() {
        // Empty the StringBuffer
        mDelayStringBuffer.setLength(0);
        // Loop over all recorded delays and append them to the buffer as a decimal
        for (int i = 0; i < mEventLength; i++) {
            if (i > 0) {
                mDelayStringBuffer.append(", ");
            }
            final int index = (mEventData + i) % EVENT_QUEUE_LENGTH;
            // convert delay from ms into s
            final float delay = mEventDelays[index] / 1000f;
            mDelayStringBuffer.append(String.format("%1.1f", delay));
        }
        return mDelayStringBuffer.toString();
    }

    /**
     * Records the state of the application into the {@link android.os.Bundle}.
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        // BEGIN_INCLUDE(saveinstance)
        super.onSaveInstanceState(outState);
        // Store all variables required to restore the state of the application
        outState.putInt(BUNDLE_LATENCY, mMaxDelay);
        outState.putInt(BUNDLE_STATE, mState);
        outState.putInt(BUNDLE_STEPS, mSteps);
    // END_INCLUDE(saveinstance)
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // BEGIN_INCLUDE(restore)
        // Fragment is being restored, reinitialise its state with data from the bundle
        if (savedInstanceState != null) {
            resetCounter();
            mSteps = savedInstanceState.getInt(BUNDLE_STEPS);
            mState = savedInstanceState.getInt(BUNDLE_STATE);
            mMaxDelay = savedInstanceState.getInt(BUNDLE_LATENCY);
            // Register listeners again if in detector or counter states with restored delay
            if (mState == STATE_DETECTOR) {
                registerEventListener(mMaxDelay, Sensor.TYPE_STEP_DETECTOR);
            } else if (mState == STATE_COUNTER) {
                // store the previous number of steps to keep  step counter count consistent
                mPreviousCounterSteps = mSteps;
                registerEventListener(mMaxDelay, Sensor.TYPE_STEP_COUNTER);
            }
        }
    // END_INCLUDE(restore)
    }

    /**
     * Hides the registration cards, reset the counter and show the step counting card.
     */
    private void showCountingCards() {
        // Hide the registration cards
        getCardStream().hideCard(CARD_REGISTER_DETECTOR);
        getCardStream().hideCard(CARD_REGISTER_COUNTER);
        // Show the explanation card if it has not been dismissed
        getCardStream().showCard(CARD_EXPLANATION);
        // Reset the step counter, then show the step counting card
        resetCounter();
        // Set the inital text for the step counting card before a step is recorded
        String sensor = "-";
        if (mState == STATE_COUNTER) {
            sensor = getString(R.string.sensor_counter);
        } else if (mState == STATE_DETECTOR) {
            sensor = getString(R.string.sensor_detector);
        }
        // Set initial text
        getCardStream().getCard(CARD_COUNTING).setreplacedle(getString(R.string.counting_replacedle, 0)).setDescription(getString(R.string.counting_description, sensor, mMaxDelay, "-"));
        // Show the counting card and make it undismissable
        getCardStream().showCard(CARD_COUNTING, false);
    }

    /**
     * Show the introduction card
     */
    private void showIntroCard() {
        Card c = new Card.Builder(this, CARD_INTRO).setreplacedle(getString(R.string.intro_replacedle)).setDescription(getString(R.string.intro_message)).build(getActivity());
        getCardStream().addCard(c, true);
    }

    /**
     * Show two registration cards, one for the step detector and counter sensors.
     */
    private void showRegisterCard() {
        // Hide the counting and explanation cards
        getCardStream().hideCard(CARD_BATCHING_DESCRIPTION);
        getCardStream().hideCard(CARD_EXPLANATION);
        getCardStream().hideCard(CARD_COUNTING);
        // Show two undismissable registration cards, one for each step sensor
        getCardStream().showCard(CARD_REGISTER_DETECTOR, false);
        getCardStream().showCard(CARD_REGISTER_COUNTER, false);
    }

    /**
     * Show the error card.
     */
    private void showErrorCard() {
        getCardStream().showCard(CARD_NOBATCHSUPPORT, false);
    }

    /**
     * Initialise Cards.
     */
    private void initialiseCards() {
        // Step counting
        Card c = new Card.Builder(this, CARD_COUNTING).setreplacedle("Steps").setDescription("").addAction("Unregister Listener", ACTION_UNREGISTER, Card.ACTION_NEGATIVE).build(getActivity());
        getCardStream().addCard(c);
        // Register step detector listener
        c = new Card.Builder(this, CARD_REGISTER_DETECTOR).setreplacedle(getString(R.string.register_detector_replacedle)).setDescription(getString(R.string.register_detector_description)).addAction(getString(R.string.register_0), ACTION_REGISTER_DETECT_NOBATCHING, Card.ACTION_NEUTRAL).addAction(getString(R.string.register_5), ACTION_REGISTER_DETECT_BATCHING_5s, Card.ACTION_NEUTRAL).addAction(getString(R.string.register_10), ACTION_REGISTER_DETECT_BATCHING_10s, Card.ACTION_NEUTRAL).build(getActivity());
        getCardStream().addCard(c);
        // Register step counter listener
        c = new Card.Builder(this, CARD_REGISTER_COUNTER).setreplacedle(getString(R.string.register_counter_replacedle)).setDescription(getString(R.string.register_counter_description)).addAction(getString(R.string.register_0), ACTION_REGISTER_COUNT_NOBATCHING, Card.ACTION_NEUTRAL).addAction(getString(R.string.register_5), ACTION_REGISTER_COUNT_BATCHING_5s, Card.ACTION_NEUTRAL).addAction(getString(R.string.register_10), ACTION_REGISTER_COUNT_BATCHING_10s, Card.ACTION_NEUTRAL).build(getActivity());
        getCardStream().addCard(c);
        // Batching description
        c = new Card.Builder(this, CARD_BATCHING_DESCRIPTION).setreplacedle(getString(R.string.batching_queue_replacedle)).setDescription(getString(R.string.batching_queue_description)).addAction(getString(R.string.action_notagain), ACTION_BATCHING_DESCRIPTION_DISMISS, Card.ACTION_POSITIVE).build(getActivity());
        getCardStream().addCard(c);
        // Explanation
        c = new Card.Builder(this, CARD_EXPLANATION).setDescription(getString(R.string.explanation_description)).addAction(getString(R.string.action_notagain), ACTION_EXPLANATION_DISMISS, Card.ACTION_POSITIVE).build(getActivity());
        getCardStream().addCard(c);
        // Error
        c = new Card.Builder(this, CARD_NOBATCHSUPPORT).setreplacedle(getString(R.string.error_replacedle)).setDescription(getString(R.string.error_nosensor)).build(getActivity());
        getCardStream().addCard(c);
    }

    /**
     * Returns the cached CardStreamFragment used to show cards.
     *
     * @return
     */
    private CardStreamFragment getCardStream() {
        if (mCards == null) {
            mCards = ((CardStream) getActivity()).getCardStream();
        }
        return mCards;
    }
}

18 Source : AccelerometerMonitor.java
with GNU General Public License v3.0
from 5GSD

/**
 * Clreplaced to handle monitoring the Accelerometer to enable/disable GPS for battery saving
 */
public clreplaced AccelerometerMonitor {

    // How long with no movement detected, before we replacedume we are not moving
    // [ms] // 10 seconds (also in LocationTracker.java)
    static final long MOVEMENT_THRESHOLD_MS = 10 * 1000;

    // amount of sensor noise to ignore
    static final float ACCELEROMETER_NOISE = 2.0f;

    private long lastMovementTime = 0;

    private float mLastX, mLastY, mLastZ;

    private boolean mInitialized;

    private SensorManager mSensorManager;

    private Sensor mAccelerometer;

    private SensorEventListener mSensorListener;

    private Runnable onMovement;

    public AccelerometerMonitor(Context context, Runnable onMovement) {
        setupAccelerometer(context);
        this.onMovement = onMovement;
    }

    /**
     * Set up the accelerometer so that when movement is detected, the GPS is enabled.
     * GPS is normally disabled to save battery power.
     */
    // TODO:
    // E:V:A  We might need to loop this once and wait a few seconds, to prevent
    // GPS from starting by accidental vibrations.
    private void setupAccelerometer(Context context) {
        // set up accelerometer sensor
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorListener = new SensorEventListener() {

            @Override
            public void onSensorChanged(SensorEvent event) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                if (!mInitialized) {
                    mInitialized = true;
                    mLastX = x;
                    mLastY = y;
                    mLastZ = z;
                } else {
                    float deltaX = Math.abs(mLastX - x);
                    float deltaY = Math.abs(mLastY - y);
                    float deltaZ = Math.abs(mLastZ - z);
                    if (deltaX < ACCELEROMETER_NOISE) {
                        deltaX = 0.0f;
                    }
                    if (deltaY < ACCELEROMETER_NOISE) {
                        deltaY = 0.0f;
                    }
                    if (deltaZ < ACCELEROMETER_NOISE) {
                        deltaZ = 0.0f;
                    }
                    mLastX = x;
                    mLastY = y;
                    mLastZ = z;
                    if (deltaX > 0 || deltaY > 0 || deltaZ > 0) {
                        // movement detected
                        // disable the movement sensor to save power
                        stop();
                        lastMovementTime = System.currentTimeMillis();
                        if (onMovement != null) {
                            Thread runThread = new Thread(onMovement);
                            runThread.start();
                        }
                    }
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        };
        start();
    }

    public void start() {
        mSensorManager.registerListener(mSensorListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void stop() {
        mSensorManager.unregisterListener(mSensorListener);
    }

    public boolean notMovedInAWhile() {
        return System.currentTimeMillis() - lastMovementTime >= MOVEMENT_THRESHOLD_MS;
    }
}

18 Source : AccelerometerService.java
with MIT License
from 0xFireball

public clreplaced AccelerometerService extends Service {

    public static final int LOCK_METHOD_DEVICE_ADMIN = 0;

    public static final int LOCK_METHOD_ROOT = 1;

    public static final int LOCK_METHOD_FAKE = 2;

    private static final int MIN_LOCK_TIME_SPACING = 10;

    public static boolean dead = false;

    private SensorManager sensorManager;

    private Sensor sensor;

    private int cycles;

    private int lastLockCycles = cycles - MIN_LOCK_TIME_SPACING;

    private SensorEventListener activeListener;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_USER_PRESENT);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(new PresenceReceiver(), intentFilter);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        activeListener = new SensorEventListener() {

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

            @Override
            public void onSensorChanged(SensorEvent event) {
                if (AccelerometerService.dead)
                    return;
                ++cycles;
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                float threshold;
                try {
                    threshold = prefs.getFloat("threshold_pref_key", 1);
                    if (threshold < SettingsActivity.MIN_THRESHOLD) {
                        // only possible pre-update.
                        threshold = SettingsActivity.DEFAULT_THRESHOLD;
                        prefs.edit().putFloat("threshold_pref_key", threshold).apply();
                    }
                } catch (ClreplacedCastException e) {
                    // The user has a non-float in the settings! Probably because they're migrating from an old version of the app.
                    String thresholdStr = prefs.getString("threshold_pref_key", "1");
                    threshold = Float.valueOf(thresholdStr);
                    prefs.edit().putFloat("threshold_pref_key", threshold).apply();
                }
                double x = Math.abs(event.values[0]);
                double y = Math.abs(event.values[1]);
                double z = Math.abs(event.values[2]);
                double total = Math.sqrt(x * x + y * y + z * z);
                if (total > threshold) {
                    // time to lock
                    int timeGap = cycles - lastLockCycles;
                    if (timeGap > MIN_LOCK_TIME_SPACING) {
                        // de-bouncing
                        lastLockCycles = cycles;
                        lockDeviceNow(AccelerometerService.this, getBaseContext());
                    }
                }
            }
        };
        sensorManager.registerListener(activeListener, sensor, SensorManager.SENSOR_DELAY_UI);
        return START_STICKY;
    }

    public static boolean lockDeviceNow(Context context, Context baseContext) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(baseContext);
        int lockMethod = prefs.getInt(PreferenceString.LOCK_METHOD, LOCK_METHOD_DEVICE_ADMIN);
        switch(lockMethod) {
            case LOCK_METHOD_DEVICE_ADMIN:
                KeyguardManager keyguardManager = (KeyguardManager) baseContext.getSystemService(Context.KEYGUARD_SERVICE);
                if (!keyguardManager.inKeyguardRestrictedInputMode()) {
                    DevicePolicyManager dpm = (DevicePolicyManager) baseContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
                    if (dpm.isAdminActive(new ComponentName(baseContext, AdminReceiver.clreplaced)))
                        dpm.lockNow();
                }
                return true;
            case LOCK_METHOD_ROOT:
                try {
                    KeyguardManager km = (KeyguardManager) baseContext.getSystemService(Context.KEYGUARD_SERVICE);
                    boolean locked = km.inKeyguardRestrictedInputMode();
                    if (!locked) {
                        // don't lock if already screen off
                        Runtime.getRuntime().exec(new String[] { "su", "-c", "input keyevent 26" }).waitFor();
                    }
                    return true;
                } catch (IOException | InterruptedException e) {
                    Toast.makeText(context, "PluckLockEx Root access denied", Toast.LENGTH_SHORT).show();
                }
            case LOCK_METHOD_FAKE:
                Toast.makeText(context, "PluckLockEx fake lock", Toast.LENGTH_SHORT).show();
                return true;
        }
        return false;
    }

    public void killSensor() {
        // THIS DOES NOT WORK.
        sensorManager.unregisterListener(activeListener);
        // workaround that may or may not actually end up improving battery life
        AccelerometerService.dead = true;
    }
}

17 Source : AccelerometerListener.java
with GNU General Public License v3.0
from XecureIT

/**
 * This clreplaced is used to listen to the accelerometer to monitor the
 * orientation of the phone. The client of this clreplaced is notified when
 * the orientation changes between horizontal and vertical.
 */
public final clreplaced AccelerometerListener {

    private static final String TAG = "AccelerometerListener";

    private static final boolean DEBUG = true;

    private static final boolean VDEBUG = false;

    private SensorManager mSensorManager;

    private Sensor mSensor;

    // mOrientation is the orientation value most recently reported to the client.
    private int mOrientation;

    // mPendingOrientation is the latest orientation computed based on the sensor value.
    // This is sent to the client after a rebounce delay, at which point it is copied to
    // mOrientation.
    private int mPendingOrientation;

    private OrientationListener mListener;

    // Device orientation
    public static final int ORIENTATION_UNKNOWN = 0;

    public static final int ORIENTATION_VERTICAL = 1;

    public static final int ORIENTATION_HORIZONTAL = 2;

    private static final int ORIENTATION_CHANGED = 1234;

    private static final int VERTICAL_DEBOUNCE = 100;

    private static final int HORIZONTAL_DEBOUNCE = 500;

    private static final double VERTICAL_ANGLE = 50.0;

    public interface OrientationListener {

        public void orientationChanged(int orientation);
    }

    public AccelerometerListener(Context context, OrientationListener listener) {
        mListener = listener;
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    public void enable(boolean enable) {
        if (DEBUG)
            Log.d(TAG, "enable(" + enable + ")");
        synchronized (this) {
            if (enable) {
                mOrientation = ORIENTATION_UNKNOWN;
                mPendingOrientation = ORIENTATION_UNKNOWN;
                mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
            } else {
                mSensorManager.unregisterListener(mSensorListener);
                mHandler.removeMessages(ORIENTATION_CHANGED);
            }
        }
    }

    private void setOrientation(int orientation) {
        synchronized (this) {
            if (mPendingOrientation == orientation) {
                // Pending orientation has not changed, so do nothing.
                return;
            }
            // Cancel any pending messages.
            // We will either start a new timer or cancel alltogether
            // if the orientation has not changed.
            mHandler.removeMessages(ORIENTATION_CHANGED);
            if (mOrientation != orientation) {
                // Set timer to send an event if the orientation has changed since its
                // previously reported value.
                mPendingOrientation = orientation;
                Message m = mHandler.obtainMessage(ORIENTATION_CHANGED);
                // set delay to our debounce timeout
                int delay = (orientation == ORIENTATION_VERTICAL ? VERTICAL_DEBOUNCE : HORIZONTAL_DEBOUNCE);
                mHandler.sendMessageDelayed(m, delay);
            } else {
                // no message is pending
                mPendingOrientation = ORIENTATION_UNKNOWN;
            }
        }
    }

    private void onSensorEvent(double x, double y, double z) {
        if (VDEBUG)
            Log.d(TAG, "onSensorEvent(" + x + ", " + y + ", " + z + ")");
        // If some values are exactly zero, then likely the sensor is not powered up yet.
        // ignore these events to avoid false horizontal positives.
        if (x == 0.0 || y == 0.0 || z == 0.0)
            return;
        // magnitude of the acceleration vector projected onto XY plane
        double xy = Math.sqrt(x * x + y * y);
        // compute the vertical angle
        double angle = Math.atan2(xy, z);
        // convert to degrees
        angle = angle * 180.0 / Math.PI;
        int orientation = (angle > VERTICAL_ANGLE ? ORIENTATION_VERTICAL : ORIENTATION_HORIZONTAL);
        if (VDEBUG)
            Log.d(TAG, "angle: " + angle + " orientation: " + orientation);
        setOrientation(orientation);
    }

    SensorEventListener mSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent event) {
            onSensorEvent(event.values[0], event.values[1], event.values[2]);
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // ignore
        }
    };

    Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch(msg.what) {
                case ORIENTATION_CHANGED:
                    synchronized (this) {
                        mOrientation = mPendingOrientation;
                        if (DEBUG) {
                            Log.d(TAG, "orientation: " + (mOrientation == ORIENTATION_HORIZONTAL ? "horizontal" : (mOrientation == ORIENTATION_VERTICAL ? "vertical" : "unknown")));
                        }
                        mListener.orientationChanged(mOrientation);
                    }
                    break;
            }
        }
    };
}

17 Source : MainActivity.java
with Apache License 2.0
from velmurugan35

public clreplaced MainActivity extends Activity {

    TextView ProximitySensor, ProximityMax, ProximityReading;

    SensorManager mySensorManager;

    Sensor myProximitySensor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ProximitySensor = (TextView) findViewById(R.id.proximitySensor);
        ProximityMax = (TextView) findViewById(R.id.proximityMax);
        ProximityReading = (TextView) findViewById(R.id.proximityReading);
        // Now in the SensorActivity we access the device sensor using SensorManager, an instance of this clreplaced is got by calling getSystemService(SENSOR_SERVICE) . We implement the clreplaced with theSensorEventListener interface to override its methods to do actions on sensor value change.
        mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        myProximitySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        if (myProximitySensor == null) {
            ProximitySensor.setText("No Proximity Sensor!");
        } else {
            ProximitySensor.setText(myProximitySensor.getName());
            ProximityMax.setText("Maximum Range: " + String.valueOf(myProximitySensor.getMaximumRange()));
            mySensorManager.registerListener(proximitySensorEventListener, myProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    SensorEventListener proximitySensorEventListener = new SensorEventListener() {

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
                ProximityReading.setText("Proximity Sensor Reading:" + String.valueOf(event.values[0]));
            }
        }
    };
}

17 Source : AccelerometerListener.java
with GNU General Public License v3.0
from treasure-lau

/**
 * This clreplaced is used to listen to the accelerometer to monitor the
 * orientation of the phone. The client of this clreplaced is notified when
 * the orientation changes between horizontal and vertical.
 */
public final clreplaced AccelerometerListener {

    private static final String TAG = "AccelerometerListener";

    private static final boolean DEBUG = true;

    private static final boolean VDEBUG = false;

    private SensorManager mSensorManager;

    private Sensor mSensor;

    // mOrientation is the orientation value most recently reported to the client.
    private int mOrientation;

    // mPendingOrientation is the latest orientation computed based on the sensor value.
    // This is sent to the client after a rebounce delay, at which point it is copied to
    // mOrientation.
    private int mPendingOrientation;

    private OrientationListener mListener;

    // Device orientation
    public static final int ORIENTATION_UNKNOWN = 0;

    public static final int ORIENTATION_VERTICAL = 1;

    public static final int ORIENTATION_HORIZONTAL = 2;

    private static final int ORIENTATION_CHANGED = 1234;

    private static final int VERTICAL_DEBOUNCE = 100;

    private static final int HORIZONTAL_DEBOUNCE = 500;

    private static final double VERTICAL_ANGLE = 50.0;

    public interface OrientationListener {

        public void orientationChanged(int orientation);
    }

    public AccelerometerListener(Context context, OrientationListener listener) {
        mListener = listener;
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    public void enable(boolean enable) {
        if (DEBUG)
            Log.d(TAG, "enable(" + enable + ")");
        synchronized (this) {
            if (enable) {
                mOrientation = ORIENTATION_UNKNOWN;
                mPendingOrientation = ORIENTATION_UNKNOWN;
                mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
            } else {
                mSensorManager.unregisterListener(mSensorListener);
                mHandler.removeMessages(ORIENTATION_CHANGED);
            }
        }
    }

    private void setOrientation(int orientation) {
        synchronized (this) {
            if (mPendingOrientation == orientation) {
                // Pending orientation has not changed, so do nothing.
                return;
            }
            // Cancel any pending messages.
            // We will either start a new timer or cancel alltogether
            // if the orientation has not changed.
            mHandler.removeMessages(ORIENTATION_CHANGED);
            if (mOrientation != orientation) {
                // Set timer to send an event if the orientation has changed since its
                // previously reported value.
                mPendingOrientation = orientation;
                Message m = mHandler.obtainMessage(ORIENTATION_CHANGED);
                // set delay to our debounce timeout
                int delay = (orientation == ORIENTATION_VERTICAL ? VERTICAL_DEBOUNCE : HORIZONTAL_DEBOUNCE);
                mHandler.sendMessageDelayed(m, delay);
            } else {
                // no message is pending
                mPendingOrientation = ORIENTATION_UNKNOWN;
            }
        }
    }

    private void onSensorEvent(double x, double y, double z) {
        if (VDEBUG)
            Log.d(TAG, "onSensorEvent(" + x + ", " + y + ", " + z + ")");
        // If some values are exactly zero, then likely the sensor is not powered up yet.
        // ignore these events to avoid false horizontal positives.
        if (x == 0.0 || y == 0.0 || z == 0.0)
            return;
        // magnitude of the acceleration vector projected onto XY plane
        double xy = Math.sqrt(x * x + y * y);
        // compute the vertical angle
        double angle = Math.atan2(xy, z);
        // convert to degrees
        angle = angle * 180.0 / Math.PI;
        int orientation = (angle > VERTICAL_ANGLE ? ORIENTATION_VERTICAL : ORIENTATION_HORIZONTAL);
        if (VDEBUG)
            Log.d(TAG, "angle: " + angle + " orientation: " + orientation);
        setOrientation(orientation);
    }

    SensorEventListener mSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent event) {
            onSensorEvent(event.values[0], event.values[1], event.values[2]);
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // ignore
        }
    };

    Handler mHandler = new AccelerometerHandler(this);

    private static clreplaced AccelerometerHandler extends Handler {

        WeakReference<AccelerometerListener> l;

        AccelerometerHandler(AccelerometerListener listener) {
            l = new WeakReference<AccelerometerListener>(listener);
        }

        public void handleMessage(Message msg) {
            AccelerometerListener listener = l.get();
            if (listener == null) {
                return;
            }
            switch(msg.what) {
                case ORIENTATION_CHANGED:
                    synchronized (listener) {
                        listener.mOrientation = listener.mPendingOrientation;
                        if (DEBUG) {
                            Log.d(TAG, "orientation: " + (listener.mOrientation == ORIENTATION_HORIZONTAL ? "horizontal" : (listener.mOrientation == ORIENTATION_VERTICAL ? "vertical" : "unknown")));
                        }
                        listener.mListener.orientationChanged(listener.mOrientation);
                    }
                    break;
            }
        }
    }
}

17 Source : TemperaturePresenter.java
with Apache License 2.0
from Samsung

public clreplaced TemperaturePresenter implements Presenter {

    /*
     * Temperature listener
     */
    private SensorEventListener temperatureListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            float temperature = event.values[0];
            if (informationPlugin != null) {
                // notify BLE
                CmdArg cmd = new CmdArg(InformationPlugin.AlertType.TYPE_TEMPERATURE, "Temperature " + temperature);
                informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
            }
        }

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

    private SensorManager sensorManager;

    private InformationPlugin informationPlugin;

    private Sensor temperatureSensor;

    private boolean isRegistered;

    public TemperaturePresenter() {
        sensorManager = (SensorManager) MBApp.getApp().getSystemService(Context.SENSOR_SERVICE);
        temperatureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    }

    public void setInformationPlugin(InformationPlugin informationPlugin) {
        this.informationPlugin = informationPlugin;
    }

    @Override
    public void start() {
        if (temperatureSensor == null) {
            // no temperature sensor
            return;
        }
        if (!isRegistered) {
            isRegistered = true;
            sensorManager.registerListener(temperatureListener, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
            if (informationPlugin != null) {
                CmdArg cmd = new CmdArg(0, "Registered Temperature.");
                informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
            }
        }
    }

    @Override
    public void stop() {
        if (temperatureSensor == null) {
            return;
        }
        if (isRegistered) {
            sensorManager.unregisterListener(temperatureListener);
            if (informationPlugin != null) {
                CmdArg cmd = new CmdArg(0, "Unregistered Temperature.");
                informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
            }
            isRegistered = false;
        }
    }

    @Override
    public void destroy() {
        stop();
    }
}

17 Source : ShakePresenter.java
with Apache License 2.0
from Samsung

public clreplaced ShakePresenter implements Presenter {

    private static final String TAG = ShakePresenter.clreplaced.getSimpleName();

    /*
     * ShakeEventListener
     */
    private SensorEventListener shakeEventListener = new SensorEventListener() {

        // nb of times swing must be detected before we call it a shake event
        static final int THRESHOLD_SWING_COUNT = 3;

        static final int SWING_EVENT_INTERVAL = 100;

        static final int SPEED_THRESHOLD = 500;

        int mSwingCount;

        long lastTime;

        float speed;

        float x, y, z;

        float lastX;

        float lastY;

        float lastZ;

        @Override
        public void onSensorChanged(SensorEvent event) {
            long currentTime = System.currentTimeMillis();
            long deltaTime = currentTime - lastTime;
            if (deltaTime > SWING_EVENT_INTERVAL) {
                lastTime = currentTime;
                x = event.values[0];
                y = event.values[1];
                z = event.values[2];
                speed = Math.abs(x + y + z - lastX - lastY - lastZ) / deltaTime * 10000;
                if (speed > SPEED_THRESHOLD) {
                    mSwingCount++;
                    if (mSwingCount >= THRESHOLD_SWING_COUNT) {
                        if (informationPlugin != null) {
                            // notify BLE client
                            CmdArg cmd = new CmdArg(InformationPlugin.AlertType.TYPE_SHAKE, "Device Shaked");
                            informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
                        }
                        MBApp application = MBApp.getApp();
                        Intent intent = new Intent(application, IPCService.clreplaced);
                        intent.putExtra(IPCConstants.INTENT_TYPE, EventCategories.IPC_BLE_NOTIFICATION_CHARACTERISTIC_CHANGED);
                        intent.putExtra(IPCConstants.INTENT_CHARACTERISTIC_MESSAGE, Utils.makeMicroBitValue(EventCategories.SAMSUNG_DEVICE_INFO_ID, EventSubCodes.SAMSUNG_DEVICE_GESTURE_DEVICE_SHAKEN));
                        application.startService(intent);
                        mSwingCount = 0;
                    }
                } else {
                    mSwingCount = 0;
                // PluginService.sendMessageToBle(Constants.makeMicroBitValue(Constants.SAMSUNG_DEVICE_INFO_ID, Constants.SAMSUNG_DEVICE_GESTURE_NONE));
                }
                lastX = x;
                lastY = y;
                lastZ = z;
            }
        }

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

    private InformationPlugin informationPlugin;

    private SensorManager sensorManager;

    private boolean isRegistered;

    public ShakePresenter() {
        sensorManager = (SensorManager) MBApp.getApp().getSystemService(Context.SENSOR_SERVICE);
    }

    public void setInformationPlugin(InformationPlugin informationPlugin) {
        this.informationPlugin = informationPlugin;
    }

    @Override
    public void start() {
        if (!isRegistered) {
            isRegistered = true;
            sensorManager.registerListener(shakeEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            if (informationPlugin != null) {
                CmdArg cmd = new CmdArg(0, "Registered Shake.");
                informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
            }
        }
    }

    @Override
    public void stop() {
        if (isRegistered) {
            sensorManager.unregisterListener(shakeEventListener);
            if (informationPlugin != null) {
                CmdArg cmd = new CmdArg(0, "Unregistered Shake.");
                informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
            }
            isRegistered = false;
        }
    }

    @Override
    public void destroy() {
        stop();
    }
}

17 Source : StabilizationService.java
with Apache License 2.0
from ryanchyshyn

public clreplaced StabilizationService extends Service {

    private static final String TAG = StabilizationService.clreplaced.getSimpleName();

    private AppSettings settings;

    private SensorManager sensorManager;

    private Sensor accelerometer;

    private boolean accListenerRegistered = false;

    private final float[] tempAcc = new float[3];

    private final float[] acc = new float[3];

    private final float[] velocity = new float[3];

    private final float[] position = new float[3];

    private long timestamp = 0;

    private int x = 0, y = 0;

    private IBinder flinger = null;

    private final SensorEventListener sensorEventListener = new SensorEventListener() {

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

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (timestamp != 0) {
                tempAcc[0] = Utils.rangeValue(event.values[0], -Constants.MAX_ACC, Constants.MAX_ACC);
                tempAcc[1] = Utils.rangeValue(event.values[1], -Constants.MAX_ACC, Constants.MAX_ACC);
                tempAcc[2] = Utils.rangeValue(event.values[2], -Constants.MAX_ACC, Constants.MAX_ACC);
                Utils.lowPreplacedFilter(tempAcc, acc, settings.getLowPreplacedAlpha());
                float dt = (event.timestamp - timestamp) * Constants.NS2S;
                for (int index = 0; index < 3; ++index) {
                    velocity[index] += acc[index] * dt - settings.getVelocityFriction() * velocity[index];
                    velocity[index] = Utils.fixNanOrInfinite(velocity[index]);
                    position[index] += velocity[index] * settings.getVelocityAmpl() * dt - settings.getPositionFriction() * position[index];
                    position[index] = Utils.rangeValue(position[index], -Constants.MAX_POS_SHIFT, Constants.MAX_POS_SHIFT);
                }
            } else {
                velocity[0] = velocity[1] = velocity[2] = 0f;
                position[0] = position[1] = position[2] = 0f;
                acc[0] = Utils.rangeValue(event.values[0], -Constants.MAX_ACC, Constants.MAX_ACC);
                acc[1] = Utils.rangeValue(event.values[1], -Constants.MAX_ACC, Constants.MAX_ACC);
                acc[2] = Utils.rangeValue(event.values[2], -Constants.MAX_ACC, Constants.MAX_ACC);
            }
            timestamp = event.timestamp;
            int newPosX = Math.round(position[0]);
            int newPosY = Math.round(position[1]);
            if ((newPosX != x) || (newPosY != y)) {
                x = newPosX;
                y = newPosY;
                setSurfaceFlingerTranslate(-x, y);
            }
        }
    };

    private final BroadcastReceiver screenOnReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Screen is on");
            setSurfaceFlingerTranslate(0, 0);
            reset();
            registerAccListener();
        }
    };

    private final BroadcastReceiver screenOffReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            unregisterAccListener();
            setSurfaceFlingerTranslate(0, 0);
            Log.d(TAG, "Screen is off");
        }
    };

    public StabilizationService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        settings = AppSettings.getAppSettings(getApplicationContext());
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        registerReceiver(screenOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
        registerReceiver(screenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
        if (Utils.isScreenOn(this))
            registerAccListener();
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(screenOnReceiver);
        unregisterReceiver(screenOffReceiver);
        unregisterAccListener();
        setSurfaceFlingerTranslate(0, 0);
        super.onDestroy();
    }

    private void reset() {
        position[0] = position[1] = position[2] = 0;
        velocity[0] = velocity[1] = velocity[2] = 0;
        acc[0] = acc[1] = acc[2] = 0;
        timestamp = 0;
        x = y = 0;
    }

    private void registerAccListener() {
        if (accListenerRegistered)
            return;
        accListenerRegistered = sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
        if (!accListenerRegistered) {
            Log.wtf(TAG, "Sensor listener not registered");
        }
    }

    private void unregisterAccListener() {
        if (accListenerRegistered) {
            accListenerRegistered = false;
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    private void setSurfaceFlingerTranslate(int x, int y) {
        try {
            if (flinger == null)
                flinger = ServiceManager.getService("SurfaceFlinger");
            if (flinger == null) {
                Log.wtf(TAG, "SurfaceFlinger is null");
                return;
            }
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken("android.ui.ISurfaceComposer");
            data.writeInt(x);
            data.writeInt(y);
            flinger.transact(2020, data, null, 0);
            data.recycle();
        } catch (Exception e) {
            Log.e(TAG, "SurfaceFlinger error", e);
        }
    }
}

17 Source : WeatherStationActivity.java
with Apache License 2.0
from retomeier

public clreplaced WeatherStationActivity extends AppCompatActivity {

    private SensorManager mSensorManager;

    private TextView mTemperatureTextView;

    private TextView mPressureTextView;

    private TextView mHumidityTextView;

    private TextView mLightTextView;

    private float mLastTemperature = Float.NaN;

    private float mLastPressure = Float.NaN;

    private float mLastLight = Float.NaN;

    private float mLastHumidity = Float.NaN;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather_station);
        mTemperatureTextView = findViewById(R.id.temperature);
        mPressureTextView = findViewById(R.id.pressure);
        mLightTextView = findViewById(R.id.light);
        mHumidityTextView = findViewById(R.id.humidity);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Timer updateTimer = new Timer("weatherUpdate");
        updateTimer.scheduleAtFixedRate(new TimerTask() {

            public void run() {
                updateGUI();
            }
        }, 0, 1000);
    }

    private final SensorEventListener mSensorEventListener = new SensorEventListener() {

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        public void onSensorChanged(SensorEvent event) {
            switch(event.sensor.getType()) {
                case (Sensor.TYPE_AMBIENT_TEMPERATURE):
                    mLastTemperature = event.values[0];
                    break;
                case (Sensor.TYPE_RELATIVE_HUMIDITY):
                    mLastHumidity = event.values[0];
                    break;
                case (Sensor.TYPE_PRESSURE):
                    mLastPressure = event.values[0];
                    break;
                case (Sensor.TYPE_LIGHT):
                    mLastLight = event.values[0];
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        Sensor lightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        if (lightSensor != null)
            mSensorManager.registerListener(mSensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        else
            mLightTextView.setText("Light Sensor Unavailable");
        Sensor pressureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        if (pressureSensor != null)
            mSensorManager.registerListener(mSensorEventListener, pressureSensor, SensorManager.SENSOR_DELAY_NORMAL);
        else
            mPressureTextView.setText("Barometer Unavailable");
        Sensor temperatureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
        if (temperatureSensor != null)
            mSensorManager.registerListener(mSensorEventListener, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
        else
            mTemperatureTextView.setText("Thermometer Unavailable");
        Sensor humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
        if (humiditySensor != null)
            mSensorManager.registerListener(mSensorEventListener, humiditySensor, SensorManager.SENSOR_DELAY_NORMAL);
        else
            mHumidityTextView.setText("Humidity Sensor Unavailable");
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mSensorEventListener);
    }

    private void updateGUI() {
        runOnUiThread(new Runnable() {

            public void run() {
                if (!Float.isNaN(mLastPressure)) {
                    mPressureTextView.setText(mLastPressure + "hPa");
                    mPressureTextView.invalidate();
                }
                if (!Float.isNaN(mLastLight)) {
                    String lightStr = "Sunny";
                    if (mLastLight <= SensorManager.LIGHT_CLOUDY)
                        lightStr = "Night";
                    else if (mLastLight <= SensorManager.LIGHT_OVERCAST)
                        lightStr = "Cloudy";
                    else if (mLastLight <= SensorManager.LIGHT_SUNLIGHT)
                        lightStr = "Overcast";
                    mLightTextView.setText(lightStr);
                    mLightTextView.invalidate();
                }
                if (!Float.isNaN(mLastTemperature)) {
                    mTemperatureTextView.setText(mLastTemperature + "C");
                    mTemperatureTextView.invalidate();
                }
                if (!Float.isNaN(mLastHumidity)) {
                    mHumidityTextView.setText(mLastHumidity + "% Rel. Humidity");
                    mHumidityTextView.invalidate();
                }
            }
        });
    }
}

17 Source : MainActivity.java
with Apache License 2.0
from retomeier

private void listing16_1_2_3_4() {
    // Listing 16-1: Determining if a type of sensor is available
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    if (sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null) {
    // TODO Barometer is available.
    } else {
    // TODO No barometer is available.
    }
    // Listing 16-2: Sensor Event Listener skeleton code
    final SensorEventListener mySensorEventListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent sensorEvent) {
        // TODO React to new Sensor result.
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO React to a change in Sensor accuracy.
        }
    };
    // Listing 16-3: Registering a Sensor Event Listener
    Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    sensorManager.registerListener(mySensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // Listing 16-4: Registering a Sensor Event Listener with a maximum Latency
        Sensor slowSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        sensorManager.registerListener(mySensorEventListener, slowSensor, SensorManager.SENSOR_DELAY_NORMAL, 10000000);
    }
}

17 Source : MainActivity.java
with Apache License 2.0
from retomeier

private void listing16_15() {
    // Listing 16-15: Finding the current alreplacedude using the barometer Sensor
    final SensorEventListener myPressureListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent sensorEvent) {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_PRESSURE) {
                float currentPressure = sensorEvent.values[0];
                // Calculate alreplacedude
                float alreplacedude = SensorManager.getAlreplacedude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, currentPressure);
            }
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };
    SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    int sensorType = Sensor.TYPE_PRESSURE;
    sm.registerListener(myPressureListener, sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
}

See More Examples