android.hardware.SensorEvent Java Examples
The following examples show how to use
android.hardware.SensorEvent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SensorService.java From wearmouse with Apache License 2.0 | 7 votes |
@Override public void onSensorChanged(SensorEvent event) { if (!registered) { return; } switch (event.sensor.getType()) { case Sensor.TYPE_GYROSCOPE: case Sensor.TYPE_GYROSCOPE_UNCALIBRATED: if (calibrating && calibrationData.add(event.values)) { if (calibrationListener != null) { calibrationListener.onCalibrationComplete(true); } stopInput(); } break; default: // fall out } }
Example #2
Source File: AnyMotionDetector.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
@Override public void onSensorChanged(SensorEvent event) { int status = RESULT_UNKNOWN; synchronized (mLock) { Vector3 accelDatum = new Vector3(SystemClock.elapsedRealtime(), event.values[0], event.values[1], event.values[2]); mRunningStats.accumulate(accelDatum); // If we have enough samples, stop accelerometer data acquisition. if (mRunningStats.getSampleCount() >= mNumSufficientSamples) { status = stopOrientationMeasurementLocked(); } } if (status != RESULT_UNKNOWN) { mHandler.removeCallbacks(mWakelockTimeout); mWakelockTimeoutIsActive = false; mCallback.onAnyMotionResult(status); } }
Example #3
Source File: MainActivity.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 6 votes |
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); }
Example #4
Source File: ShakeDetector.java From react-native-GPay with MIT License | 6 votes |
@Override public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.timestamp - mLastTimestamp < MIN_TIME_BETWEEN_SAMPLES_NS) { return; } float ax = sensorEvent.values[0]; float ay = sensorEvent.values[1]; float az = sensorEvent.values[2] - SensorManager.GRAVITY_EARTH; mLastTimestamp = sensorEvent.timestamp; if (atLeastRequiredForce(ax) && ax * mAccelerationX <= 0) { recordShake(sensorEvent.timestamp); mAccelerationX = ax; } else if (atLeastRequiredForce(ay) && ay * mAccelerationY <= 0) { recordShake(sensorEvent.timestamp); mAccelerationY = ay; } else if (atLeastRequiredForce(az) && az * mAccelerationZ <= 0) { recordShake(sensorEvent.timestamp); mAccelerationZ = az; } maybeDispatchShake(sensorEvent.timestamp); }
Example #5
Source File: SensorMyLocationOverlay.java From WhereYouGo with GNU General Public License v3.0 | 6 votes |
@Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { boolean redraw = false; synchronized (this) { long timestamp = event.timestamp / 1000000; float azimuth = (event.values[0] + getRotationOffset() + 360) % 360; azimuth = filterValue(azimuth, this.currentCompassAzimuth); this.currentCompassAzimuth = azimuth; this.marker.setRotation(azimuth); if (Math.abs(timestamp - this.lastCompassTimestamp) >= UPDATE_INTERVAL && Math.abs(azimuth - this.lastCompassAzimuth) >= UPDATE_AZIMUTH) { this.lastCompassTimestamp = timestamp; this.lastCompassAzimuth = azimuth; redraw = true; } } if (redraw) this.mapView.getOverlayController().redrawOverlays(); } }
Example #6
Source File: StreamActivity.java From Twire with GNU General Public License v3.0 | 6 votes |
@Override public void onSensorChanged(SensorEvent event) { try { if (event.sensor == mRotationSensor && getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { if (event.values.length > 4) { float[] truncatedRotationVector = new float[4]; System.arraycopy(event.values, 0, truncatedRotationVector, 0, 4); update(truncatedRotationVector); } else { update(event.values); } } } catch (Exception e) { e.printStackTrace(); } }
Example #7
Source File: VoIPBaseService.java From TelePlus-Android with GNU General Public License v2.0 | 6 votes |
@SuppressLint("NewApi") @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { AudioManager am=(AudioManager) getSystemService(AUDIO_SERVICE); if (isHeadsetPlugged || am.isSpeakerphoneOn() || (isBluetoothHeadsetConnected() && am.isBluetoothScoOn())) { return; } boolean newIsNear = event.values[0] < Math.min(event.sensor.getMaximumRange(), 3); if (newIsNear != isProximityNear) { if (BuildVars.LOGS_ENABLED) { FileLog.d("proximity " + newIsNear); } isProximityNear = newIsNear; try{ if(isProximityNear){ proximityWakelock.acquire(); }else{ proximityWakelock.release(1); // this is non-public API before L } }catch(Exception x){ FileLog.e(x); } } } }
Example #8
Source File: ControllerFragment.java From Bluefruit_LE_Connect_Android_V2 with MIT License | 6 votes |
@Override public void onSensorChanged(SensorEvent event) { int sensorType = event.sensor.getType(); if (sensorType == Sensor.TYPE_ACCELEROMETER) { mSensorData[kSensorType_Accelerometer].values = event.values; updateOrientation(); // orientation depends on Accelerometer and Magnetometer mControllerAdapter.notifySensorChanged(kSensorType_Accelerometer); mControllerAdapter.notifySensorChanged(kSensorType_Quaternion); } else if (sensorType == Sensor.TYPE_GYROSCOPE) { mSensorData[kSensorType_Gyroscope].values = event.values; mControllerAdapter.notifySensorChanged(kSensorType_Gyroscope); } else if (sensorType == Sensor.TYPE_MAGNETIC_FIELD) { mSensorData[kSensorType_Magnetometer].values = event.values; updateOrientation(); // orientation depends on Accelerometer and Magnetometer mControllerAdapter.notifySensorChanged(kSensorType_Magnetometer); mControllerAdapter.notifySensorChanged(kSensorType_Quaternion); } }
Example #9
Source File: AeyriumSensorPlugin.java From aeyrium-sensor with MIT License | 6 votes |
SensorEventListener createSensorEventListener(final EventChannel.EventSink events) { return new SensorEventListener() { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { if (mLastAccuracy != accuracy) { mLastAccuracy = accuracy; } } @Override public void onSensorChanged(SensorEvent event) { if (mLastAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { return; } updateOrientation(event.values, events); } }; }
Example #10
Source File: ScreenSensorAssist.java From DevUtils with Apache License 2.0 | 6 votes |
@Override 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 - Math.round(angle); // normalize to 0 - 359 range while (orientation >= 360) { orientation -= 360; } while (orientation < 0) { orientation += 360; } } if (mRotateHandler != null) { mRotateHandler.obtainMessage(CHANGE_ORIENTATION_WHAT, orientation, 0).sendToTarget(); } }
Example #11
Source File: SensorInterpreter.java From VideoOS-Android-SDK with GNU General Public License v3.0 | 6 votes |
@NonNull float[] getRotationVectorFromSensorEvent(@NonNull SensorEvent event) { if (event.values.length > 4) { // On some Samsung devices SensorManager.getRotationMatrixFromVector // appears to throw an exception if rotation vector has length > 4. // For the purposes of this class the first 4 values of the // rotation vector are sufficient (see crbug.com/335298 for details). if (mTruncatedRotationVector == null) { mTruncatedRotationVector = new float[4]; } System.arraycopy(event.values, 0, mTruncatedRotationVector, 0, 4); return mTruncatedRotationVector; } else { return event.values; } }
Example #12
Source File: MainActivity.java From Android-9-Development-Cookbook with MIT License | 6 votes |
private void calculateCompassDirection(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: mAccelerationValues = event.values.clone(); break; case Sensor.TYPE_MAGNETIC_FIELD: mGravityValues = event.values.clone(); break; } boolean success = SensorManager.getRotationMatrix(mRotationMatrix, null, mAccelerationValues, mGravityValues); if (success) { float[] orientationValues = new float[3]; SensorManager.getOrientation(mRotationMatrix, orientationValues); float azimuth = (float) Math.toDegrees(-orientationValues[0]); RotateAnimation rotateAnimation = new RotateAnimation(mLastDirectionInDegrees, azimuth, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnimation.setDuration(50); rotateAnimation.setFillAfter(true); mImageViewCompass.startAnimation(rotateAnimation); mLastDirectionInDegrees = azimuth; } }
Example #13
Source File: AppRTCProximitySensor.java From flutter-incall-manager with ISC License | 6 votes |
@Override public final void onSensorChanged(SensorEvent event) { // As a best practice; do as little as possible within this method and // avoid blocking. float distanceInCentimeters = event.values[0]; if (distanceInCentimeters < proximitySensor.getMaximumRange()) { Log.d(TAG, "Proximity sensor => NEAR state"); lastStateReportIsNear = true; } else { Log.d(TAG, "Proximity sensor => FAR state"); lastStateReportIsNear = false; } // Report about new state to listening client. Client can then call // sensorReportsNearState() to query the current state (NEAR or FAR). if (onSensorStateListener != null) { onSensorStateListener.run(); } Log.d(TAG, "onSensorChanged" + ": " + "accuracy=" + event.accuracy + ", timestamp=" + event.timestamp + ", distance=" + event.values[0]); }
Example #14
Source File: MotionStrategy.java From Beginner-Level-Android-Studio-Apps with GNU General Public License v3.0 | 6 votes |
@Override public void onSensorChanged(final SensorEvent event) { if (isOn && event.accuracy != 0){ if (getParams().mSensorListener != null){ getParams().mSensorListener.onSensorChanged(event); } int type = event.sensor.getType(); switch (type){ case Sensor.TYPE_ROTATION_VECTOR: // post VRUtil.sensorRotationVector2Matrix(event, windowManager.getDefaultDisplay().getRotation(), mSensorMatrix); // mTmpMatrix will be used in multi thread. synchronized (mMatrixLock){ System.arraycopy(mSensorMatrix, 0, mTmpMatrix, 0, 16); } getParams().glHandler.post(updateSensorRunnable); break; } } }
Example #15
Source File: SensorAccelerometer.java From VideoRecorder with Apache License 2.0 | 6 votes |
@Override public void onSensorChanged(SensorEvent event) { if (mListener == null || event.sensor == null) return; if (event.sensor.getType() == android.hardware.Sensor.TYPE_ACCELEROMETER) { int x = (int) event.values[0]; int y = (int) event.values[1]; if (Math.abs(x) > 6) {// 倾斜度超过60度 10*1.732/2 if (x <= -3) mListener.onChange(0); else mListener.onChange(1); } else { if (y <= -3) mListener.onChange(2); else mListener.onChange(3); } } }
Example #16
Source File: AppRTCProximitySensor.java From imsdk-android with MIT License | 6 votes |
@Override public final void onSensorChanged(SensorEvent event) { threadChecker.checkIsOnValidThread(); AppRTCUtils.assertIsTrue(event.sensor.getType() == Sensor.TYPE_PROXIMITY); // As a best practice; do as little as possible within this method and // avoid blocking. float distanceInCentimeters = event.values[0]; if (distanceInCentimeters < proximitySensor.getMaximumRange()) { LogUtil.d(TAG, "Proximity sensor => NEAR state"); lastStateReportIsNear = true; } else { LogUtil.d(TAG, "Proximity sensor => FAR state"); lastStateReportIsNear = false; } // Report about new state to listening client. Client can then call // sensorReportsNearState() to query the current state (NEAR or FAR). if (onSensorStateListener != null) { onSensorStateListener.run(); } LogUtil.d(TAG, "onSensorChanged" + AppRTCUtils.getThreadInfo() + ": " + "accuracy=" + event.accuracy + ", timestamp=" + event.timestamp + ", distance=" + event.values[0]); }
Example #17
Source File: OrientationSensorListener.java From sealrtc-android with MIT License | 6 votes |
@Override 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 (rotateHandler != null) { rotateHandler.obtainMessage(888, orientation, 0).sendToTarget(); } }
Example #18
Source File: AudioSlidePlayer.java From mollyim-android with GNU General Public License v3.0 | 5 votes |
@Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() != Sensor.TYPE_PROXIMITY) return; if (mediaPlayer == null || mediaPlayer.getPlaybackState() != Player.STATE_READY) return; int streamType; if (event.values[0] < 5f && event.values[0] != proximitySensor.getMaximumRange()) { streamType = AudioManager.STREAM_VOICE_CALL; } else { streamType = AudioManager.STREAM_MUSIC; } if (streamType == AudioManager.STREAM_VOICE_CALL && mediaPlayer.getAudioStreamType() != streamType && !audioManager.isWiredHeadsetOn()) { double position = mediaPlayer.getCurrentPosition(); double duration = mediaPlayer.getDuration(); double progress = position / duration; if (wakeLock != null) wakeLock.acquire(); stop(); try { play(progress, true); } catch (IOException e) { Log.w(TAG, e); } } else if (streamType == AudioManager.STREAM_MUSIC && mediaPlayer.getAudioStreamType() != streamType && System.currentTimeMillis() - startTime > 500) { if (wakeLock != null) wakeLock.release(); stop(); notifyOnStop(); } }
Example #19
Source File: ScreenSensorAssist.java From DevUtils with Apache License 2.0 | 5 votes |
@Override 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 - Math.round(angle); // normalize to 0 - 359 range while (orientation >= 360) { orientation -= 360; } while (orientation < 0) { orientation += 360; } } if (orientation > 225 && orientation < 315) { // 检测到当前实际是横屏 if (!mPortrait) { mSensorManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_UI); mSensorManagerChange.unregisterListener(mListenerChange); } } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) { // 检测到当前实际是竖屏 if (mPortrait) { mSensorManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_UI); mSensorManagerChange.unregisterListener(mListenerChange); } } }
Example #20
Source File: BatchStepSensorFragment.java From sensors-samples with Apache License 2.0 | 5 votes |
/** * 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; }
Example #21
Source File: MeiFireflyActivity.java From kAndroid with Apache License 2.0 | 5 votes |
@Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float x = event.values[0]; float y = event.values[1] * 2.0f; mMobikeView.onSensorChanged(-x, y); } }
Example #22
Source File: Jzvd.java From imsdk-android with MIT License | 5 votes |
@Override public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值 final float x = event.values[SensorManager.DATA_X]; float y = event.values[SensorManager.DATA_Y]; float z = event.values[SensorManager.DATA_Z]; //过滤掉用力过猛会有一个反向的大数值 if (x < -12 || x > 12) { if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000) { if (Jzvd.CURRENT_JZVD != null) Jzvd.CURRENT_JZVD.autoFullscreen(x); lastAutoFullscreenTime = System.currentTimeMillis(); } } }
Example #23
Source File: CameraInterface.java From imsdk-android with MIT License | 5 votes |
public void onSensorChanged(SensorEvent event) { if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) { return; } float[] values = event.values; angle = AngleUtil.getSensorAngle(values[0], values[1]); rotationAnimation(); }
Example #24
Source File: CameraInterface.java From imsdk-android with MIT License | 5 votes |
public void onSensorChanged(SensorEvent event) { if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) { return; } float[] values = event.values; angle = AngleUtil.getSensorAngle(values[0], values[1]); rotationAnimation(); }
Example #25
Source File: TempSensorBreadcrumbsIntegration.java From sentry-android with MIT License | 5 votes |
@Override public void onSensorChanged(SensorEvent event) { final float[] values = event.values; // return if data is not available or zero'ed if (values == null || values.length == 0 || values[0] == 0f) { return; } if (hub != null) { final Breadcrumb breadcrumb = new Breadcrumb(); breadcrumb.setType("system"); breadcrumb.setCategory("device.event"); breadcrumb.setData("action", "TYPE_AMBIENT_TEMPERATURE"); breadcrumb.setData("accuracy", event.accuracy); breadcrumb.setData("timestamp", event.timestamp); breadcrumb.setLevel(SentryLevel.INFO); breadcrumb.setData("degree", event.values[0]); // Celsius hub.addBreadcrumb(breadcrumb); } }
Example #26
Source File: MagneticSensor.java From SensorsAndAi with MIT License | 5 votes |
public void onSensorChanged(SensorEvent sensorEvent) { float azimuthal = Math.round ( sensorEvent.values[0] ); float pitch = Math.round ( sensorEvent.values[1] ); float roll= Math.round ( sensorEvent.values[2] ); double tesla = Math.sqrt ( (azimuthal*azimuthal)+(pitch*pitch)+(roll*roll) ); String text =String.format ( "%.0f",tesla ); textView.setText ( text +"µT" ); }
Example #27
Source File: PedometerPlugin.java From flutter-plugins with MIT License | 5 votes |
SensorEventListener createSensorEventListener(final EventChannel.EventSink events) { return new SensorEventListener() { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @TargetApi(Build.VERSION_CODES.CUPCAKE) @Override public void onSensorChanged(SensorEvent event) { int stepCount = (int) event.values[0]; events.success(stepCount); } }; }
Example #28
Source File: JZVideoPlayer.java From JZVideoDemo with MIT License | 5 votes |
@Override public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值 final float x = event.values[SensorManager.DATA_X]; float y = event.values[SensorManager.DATA_Y]; float z = event.values[SensorManager.DATA_Z]; //过滤掉用力过猛会有一个反向的大数值 if (x < -12 || x > 12) { if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000) { if (JZVideoPlayerManager.getCurrentJzvd() != null) { JZVideoPlayerManager.getCurrentJzvd().autoFullscreen(x); } lastAutoFullscreenTime = System.currentTimeMillis(); } } }
Example #29
Source File: AudioSourceSwitcher.java From android-auto-call-recorder with MIT License | 5 votes |
@Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) { //near Log.d(TAG, "near"); playOnEarpiece(); } else { //far Log.d(TAG, "far"); playOnSpeaker(); } } }
Example #30
Source File: LVImageView.java From VideoOS-Android-SDK with GNU General Public License v3.0 | 5 votes |
@Override public void onSensorChanged(SensorEvent event) { if (mSensorInterpreter == null) return; float[] vectors = mSensorInterpreter.interpretSensorEvent(getContext(), event); // Return if interpretation of data failed if (vectors == null) return; // Set translation on ImageView matrix setTranslate(vectors[2], -vectors[1]); }