下面列出了怎么用android.hardware.SensorEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@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
}
}
/** The device has moved. We need to decide if it was intentional or not. */
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
float gX = x / SensorManager.GRAVITY_EARTH;
float gY = y / SensorManager.GRAVITY_EARTH;
float gZ = z / SensorManager.GRAVITY_EARTH;
double gForce = Math.sqrt(gX * gX + gY * gY + gZ * gZ);
if (gForce > SHAKE_THRESHOLD_GRAVITY && getState() == State.DISCOVERING) {
logD("Device shaken");
vibrate();
setState(State.ADVERTISING);
postDelayed(mDiscoverRunnable, ADVERTISING_DURATION);
}
}
@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);
}
}
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);
}
@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);
}
}
@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();
}
}
@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();
}
}
@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);
}
}
}
}
@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);
}
@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);
}
}
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);
}
};
}
@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]);
}
@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();
}
}
@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;
}
}
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;
}
}
@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]);
}
@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;
}
}
}
@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);
}
}
}
@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();
}
}
@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();
}
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == 3) {
this.listener.onSensorChanged(event.values[0]);
} else if (event.sensor.getType() == 6) {
X8PressureGpsInfo.getInstance().sethPa(event.values[0]);
X8PressureGpsInfo.getInstance().setHasPressure(true);
}
}
/**
* 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;
}
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 lux = (int) event.values[0];
events.success(lux);
}
};
}
@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 onSensorChanged(SensorEvent event) {
if (mProximitySensorEnabled) {
final long time = SystemClock.uptimeMillis();
final float distance = event.values[0];
boolean positive = distance >= 0.0f && distance < mProximityThreshold;
handleProximitySensorEvent(time, positive);
}
}
private void recordSensorEvent(SensorEvent event) {
long horizon = mInjector.elapsedRealtimeNanos() - LUX_EVENT_HORIZON;
synchronized (mDataCollectionLock) {
if (DEBUG) {
Slog.v(TAG, "Sensor event " + event);
}
if (!mLastSensorReadings.isEmpty()
&& event.timestamp < mLastSensorReadings.getLast().timestamp) {
// Ignore event that came out of order.
return;
}
LightData data = null;
while (!mLastSensorReadings.isEmpty()
&& mLastSensorReadings.getFirst().timestamp < horizon) {
// Remove data that has fallen out of the window.
data = mLastSensorReadings.removeFirst();
}
// We put back the last one we removed so we know how long
// the first sensor reading was valid for.
if (data != null) {
mLastSensorReadings.addFirst(data);
}
data = new LightData();
data.timestamp = event.timestamp;
data.lux = event.values[0];
mLastSensorReadings.addLast(data);
}
}
@Override
public void onSensorChanged(SensorEvent event) {
synchronized (DeviceIdleController.this) {
mSensorManager.unregisterListener(this, mMotionSensor);
active = false;
motionLocked();
}
}
@Override
public final void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
double laX = event.values[0];
double laY = event.values[1];
double laZ = event.values[2];
double laTotal = Math.sqrt(Math.pow(laX, 2)
+ Math.pow(laY, 2)
+ Math.pow(laZ, 2));
if (state == State.Normal && laTotal < FALL_THRESHOLD) {
state = State.Fall;
fallTimestamp = System.currentTimeMillis();
Intent intent = new Intent(NaviBeeApplication.getInstance(), SosActivity.class);
intent.putExtra("fall_detection", true);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
NaviBeeApplication.getInstance().startActivity(intent);
} else if (System.currentTimeMillis() >= fallTimestamp + 2000) {
state = State.Normal;
}
}
}
@Override
public void onSensorChanged(SensorEvent event) {
int newRotation;
synchronized (mLock) {
mDesiredRotation = (int) event.values[0];
newRotation = evaluateRotationChangeLocked();
}
if (newRotation >=0) {
onProposedRotationChanged(newRotation);
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
final float alpha= 0.97f;
synchronized (this){
if (sensorEvent.sensor.getType ()==Sensor.TYPE_ACCELEROMETER){
mGravity[0]= alpha*mGravity[0]+(1-alpha)*sensorEvent.values[0];
mGravity[1]= alpha*mGravity[1]+(1-alpha)*sensorEvent.values[1];
mGravity[2]= alpha*mGravity[2]+(1-alpha)*sensorEvent.values[2];
}
if (sensorEvent.sensor.getType ()==Sensor.TYPE_MAGNETIC_FIELD){
mGeomagnetic[0]= alpha*mGeomagnetic[0]+(1-alpha)*sensorEvent.values[0];
mGeomagnetic[1]= alpha*mGeomagnetic[1]+(1-alpha)*sensorEvent.values[1];
mGeomagnetic[2]= alpha*mGeomagnetic[2]+(1-alpha)*sensorEvent.values[2];
}
float R[] =new float[9];
float I[] =new float[9];
boolean success = SensorManager.getRotationMatrix ( R,I,mGravity,mGeomagnetic );
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation ( R,orientation );
azimuth =(float)Math.toDegrees ( orientation[0] );
azimuth = (azimuth+360)%360;
//
Animation anim =new RotateAnimation ( -correctAzimuth,-azimuth, Animation.RELATIVE_TO_SELF,0.5f
,Animation.RELATIVE_TO_SELF,0.5f);
correctAzimuth = azimuth;
anim.setDuration ( 500 );
anim.setRepeatCount ( 0 );
anim.setFillAfter ( true );
imageView.startAnimation ( anim );
}
}
}