Java Code Examples for android.hardware.SensorEvent

The following are top voted examples for showing how to use android.hardware.SensorEvent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xlight_android_native   File: SlidingMenuMainActivity.java   View source code 6 votes vote down vote up
@Override
        public void onSensorChanged(SensorEvent event) {
            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度,向右为正
            float y = values[1]; // y轴方向的重力加速度,向前为正
            float z = values[2]; // z轴方向的重力加速度,向上为正
//            Log.i("xlight", "x轴方向的重力加速度" + x + ";y轴方向的重力加速度" + y + ";z轴方向的重力加速度" + z);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            //Logger.i("shake", "x = " + Math.abs(x) + ",y = " + y + ",z = " + z);
            int medumValue = 18;// 三星 i9250怎么晃都不会超过20,没办法,只设置19了
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {

                if (!UserUtils.isLogin(SlidingMenuMainActivity.this) || null == mShakeInfo) {
                    return;
                }

                vibrator.vibrate(200);
                Message msg = new Message();
                msg.what = SENSOR_SHAKE;
                handler.sendMessage(msg);
            }
        }
 
Example 2
Project: homescreenarcade   File: SpaceInvadersActivity.java   View source code 6 votes vote down vote up
private void accelerometerControl(SensorEvent event) {
		float xSens;
		
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
            return;

        xSens = event.values[1];
//        if(xSens > mAccelerometerThreshold){
//        	mMove = true;
//        	mMoveLeft = false;
//        	mTouch = true;
//        	return;
//        }
//        if(xSens < -mAccelerometerThreshold){
//        	mMove = true;
//        	mTouch = true;
//        	mMoveLeft = true;
//        	return;
//        }
//        mMove = false;
//        if(mFire == false){
//        	mTouch = false;
//        }
	}
 
Example 3
Project: RNLearn_Project1   File: ShakeDetector.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
  if (sensorEvent.timestamp - mLastTimestamp < MIN_TIME_BETWEEN_SAMPLES_MS) {
    return;
  }

  Assertions.assertNotNull(mTimestamps);
  Assertions.assertNotNull(mMagnitudes);

  float ax = sensorEvent.values[0];
  float ay = sensorEvent.values[1];
  float az = sensorEvent.values[2];

  mLastTimestamp = sensorEvent.timestamp;
  mTimestamps[mCurrentIndex] = sensorEvent.timestamp;
  mMagnitudes[mCurrentIndex] = Math.sqrt(ax * ax + ay * ay + az * az);

  maybeDispatchShake(sensorEvent.timestamp);

  mCurrentIndex = (mCurrentIndex + 1) % MAX_SAMPLES;
}
 
Example 4
Project: react-native-camera-face-detector   File: RCTSensorOrientationChecker.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    float x = event.values[0];
    float y = event.values[1];

    if (x<5 && x>-5 && y > 5)
        mOrientation = Surface.ROTATION_0; // portrait
    else if (x<-5 && y<5 && y>-5)
        mOrientation = Surface.ROTATION_270; // right
    else if (x<5 && x>-5 && y<-5)
        mOrientation = Surface.ROTATION_180; // upside down
    else if (x>5 && y<5 && y>-5)
        mOrientation = Surface.ROTATION_90; // left

    if (mListener != null) {
        mListener.orientationEvent();
    }
}
 
Example 5
Project: ActivityStack   File: ShakeDetector.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    if (sensorEvent.timestamp - mLastTimestamp < MIN_TIME_BETWEEN_SAMPLES_MS) {
        return;
    }

    float ax = sensorEvent.values[0];
    float ay = sensorEvent.values[1];
    float az = sensorEvent.values[2];

    mLastTimestamp = sensorEvent.timestamp;
    mTimestamps[mCurrentIndex] = sensorEvent.timestamp;
    mMagnitudes[mCurrentIndex] = Math.sqrt(ax * ax + ay * ay + az * az);

    maybeDispatchShake(sensorEvent.timestamp);

    mCurrentIndex = (mCurrentIndex + 1) % MAX_SAMPLES;
}
 
Example 6
Project: Pocket-Plays-for-Twitch   File: StreamActivity.java   View source code 6 votes vote down vote up
@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
Project: microbit   File: OrientationChangedPresenter.java   View source code 6 votes vote down vote up
@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.class);
        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;
    }
}
 
Example 8
Project: SmartOrnament   File: ShakeService.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    // 传感器信息改变时执行该方法
    float[] values = event.values;
    float x = values[0]; // x轴方向的重力加速度,向右为正
    float y = values[1]; // y轴方向的重力加速度,向前为正
    float z = values[2]; // z轴方向的重力加速度,向上为正
    //	Log.i(TAG, "x轴方向的重力加速度" + x +  ";y轴方向的重力加速度" + y +  ";z轴方向的重力加速度" + z);
    // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
    int medumValue = 30;
    if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
        Log.i("Test5555", "x轴方向的重力加速度" + x + ";y轴方向的重力加速度" + y + ";z轴方向的重力加速度" + z);
        vibrator.vibrate(200);
        Message msg = new Message();
        msg.what = SENSOR_SHAKE;
        handler.sendMessage(msg);
    }
}
 
Example 9
Project: MyFire   File: JCVideoPlayer.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值
    float x = event.values[SensorManager.DATA_X];
    float y = event.values[SensorManager.DATA_Y];
    float z = event.values[SensorManager.DATA_Z];
    if (x < -10) {
        //direction right
    } else if (x > 10) {
        //direction left
        if (JCVideoPlayerManager.listener() != null) {
            JCVideoPlayerManager.listener().autoFullscreenLeft();
        }
    } else if (y > 9.5) {
        if (JCVideoPlayerManager.listener() != null) {
            JCVideoPlayerManager.listener().autoQuitFullscreen();
        }
    }

}
 
Example 10
Project: boohee_v5.6   File: af.java   View source code 6 votes vote down vote up
public void onSensorChanged(SensorEvent sensorEvent) {
    switch (sensorEvent.sensor.getType()) {
        case 1:
            this.g4 = sensorEvent.values;
            break;
        case 2:
            this.g8 = sensorEvent.values;
            break;
    }
    if (this.g4 != null && this.g8 != null) {
        float[] fArr = new float[9];
        if (SensorManager.getRotationMatrix(fArr, null, this.g4, this.g8)) {
            float[] fArr2 = new float[3];
            SensorManager.getOrientation(fArr, fArr2);
            g5 = (float) Math.toDegrees((double) fArr2[0]);
            g5 = (float) Math.floor(g5 >= 0.0f ? (double) g5 : (double) (g5 + 360.0f));
        }
    }
}
 
Example 11
Project: Android-SteamVR-controller   File: AccelerometerCompassProvider.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    // we received a sensor event. it is a good practice to check
    // that we received the proper event
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        System.arraycopy(event.values, 0, magnitudeValues, 0, magnitudeValues.length);
    } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length);
    }

    if (magnitudeValues != null && accelerometerValues != null) {
        // Fuse accelerometer with compass
        SensorManager.getRotationMatrix(currentOrientationRotationMatrix.matrix, inclinationValues, accelerometerValues,
                magnitudeValues);
        // Transform rotation matrix to quaternion
        currentOrientationQuaternion.setRowMajor(currentOrientationRotationMatrix.matrix);
    }
}
 
Example 12
Project: Android-SteamVR-controller   File: GravityCompassProvider.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    // we received a sensor event. it is a good practice to check
    // that we received the proper event
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        System.arraycopy(event.values, 0, magnitudeValues, 0, magnitudeValues.length);
    } else if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
        System.arraycopy(event.values, 0, gravityValues, 0, gravityValues.length);
    }

    if (magnitudeValues != null && gravityValues != null) {
        // Fuse gravity-sensor (virtual sensor) with compass
        SensorManager.getRotationMatrix(currentOrientationRotationMatrix.matrix, inclinationValues, gravityValues, magnitudeValues);
        // Transform rotation matrix to quaternion
        currentOrientationQuaternion.setRowMajor(currentOrientationRotationMatrix.matrix);
    }
}
 
Example 13
Project: 2017.2-codigo   File: SensorSingleValueActivity.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    Float[] values = new Float[3];
    values[0] = event.values[0];
    updateValues(values);
    //event.accuracy
    //event.sensor
    //event.timestamp

    //Don't block the onSensorChanged() method
    /*
    Sensor data can change at a high rate, which means the system may call the
    onSensorChanged(SensorEvent) method quite often. As a best practice, you
    should do as little as possible within the onSensorChanged(SensorEvent) method
    so you don't block it. If your application requires you to do any data filtering
    or reduction of sensor data, you should perform that work outside of the
    onSensorChanged(SensorEvent) method.
    */
}
 
Example 14
Project: KomaMusic   File: ShakeDetector.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    boolean accelerating = isAccelerating(event);
    long timestamp = event.timestamp;
    queue.add(timestamp, accelerating);
    if (queue.isShaking()) {
        /*
         * detect time between two concecutive shakes and limit it to
         * MIN_TIME_BETWEEN_TWO_SHAKES
         */
        long currentTime = System.currentTimeMillis();
        if (currentTime - mDetectedShakeStartTime > MIN_TIME_BETWEEN_TWO_SHAKES) {
            queue.clear();
            listener.hearShake();
            mDetectedShakeStartTime = System.currentTimeMillis();
        }
    }
}
 
Example 15
Project: Android-SteamVR-controller   File: RotationVectorProvider.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    // we received a sensor event. it is a good practice to check
    // that we received the proper event
    if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
        // convert the rotation-vector to a 4x4 matrix. the matrix
        // is interpreted by Open GL as the inverse of the
        // rotation-vector, which is what we want.
        SensorManager.getRotationMatrixFromVector(currentOrientationRotationMatrix.matrix, event.values);

        // Get Quaternion
        // Calculate angle. Starting with API_18, Android will provide this value as event.values[3], but if not, we have to calculate it manually.
        SensorManager.getQuaternionFromVector(temporaryQuaternion, event.values);
        currentOrientationQuaternion.setXYZW(temporaryQuaternion[1], temporaryQuaternion[2], temporaryQuaternion[3], -temporaryQuaternion[0]);
    }
}
 
Example 16
Project: GankIO_weex   File: ShakeDetector.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
  if (sensorEvent.timestamp - mLastTimestamp < MIN_TIME_BETWEEN_SAMPLES_MS) {
    return;
  }

  Assertions.assertNotNull(mTimestamps);
  Assertions.assertNotNull(mMagnitudes);

  float ax = sensorEvent.values[0];
  float ay = sensorEvent.values[1];
  float az = sensorEvent.values[2];

  mLastTimestamp = sensorEvent.timestamp;
  mTimestamps[mCurrentIndex] = sensorEvent.timestamp;
  mMagnitudes[mCurrentIndex] = Math.sqrt(ax * ax + ay * ay + az * az);

  maybeDispatchShake(sensorEvent.timestamp);

  mCurrentIndex = (mCurrentIndex + 1) % MAX_SAMPLES;
}
 
Example 17
Project: sctalk   File: MessageActivity.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent arg0) {
    try {
        if (!AudioPlayerHandler.getInstance().isPlaying()) {
            return;
        }
        float range = arg0.values[0];
        if (null != sensor && range == sensor.getMaximumRange()) {
            // 屏幕恢复亮度
            AudioPlayerHandler.getInstance().setAudioMode(AudioManager.MODE_NORMAL, this);
        } else {
            // 屏幕变黑
            AudioPlayerHandler.getInstance().setAudioMode(AudioManager.MODE_IN_CALL, this);
        }
    } catch (Exception e) {
        logger.error(e);
    }
}
 
Example 18
Project: nc-android-webrtcpeer   File: ProximitySensor.java   View source code 6 votes vote down vote up
@Override
public final void onSensorChanged(SensorEvent event) {
    threadChecker.checkIsOnValidThread();
    Utils.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()) {
        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" + Utils.getThreadInfo() + ": "
               + "accuracy=" + event.accuracy + ", timestamp=" + event.timestamp + ", distance="
               + event.values[0]);
}
 
Example 19
Project: PDR   File: StepDetector.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
	// TODO Auto-generated method stub
	switch (event.sensor.getType()) {
	case Sensor.TYPE_ACCELEROMETER:
		
		break;
	case Sensor.TYPE_GRAVITY:
		vGravity = event.values.clone();
		mPhy = (float) Math.atan(Math.abs(vGravity[2]/vGravity[1]));
		break;
	case Sensor.TYPE_LINEAR_ACCELERATION:
		vLinAcceleration = event.values.clone();
		detectStep(vLinAcceleration, mPhy);
		break;
	default:
		break;
	}
}
 
Example 20
Project: CoolClock   File: ProximityService.java   View source code 6 votes vote down vote up
@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.class.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...");
            }
        }
    }
}
 
Example 21
Project: mapbox-plugins-android   File: CompassManager.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
  if (internalCompassListener == null) {
    return;
  }
  // check when the last time the compass was updated, return if too soon.
  long currentTime = SystemClock.elapsedRealtime();
  if (currentTime < compassUpdateNextTimestamp) {
    return;
  }
  if (lastAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
    Timber.d("Compass sensor is unreliable, device calibration is needed.");
    return;
  }
  if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
    updateOrientation(event.values);

    // Update the compassUpdateNextTimestamp
    compassUpdateNextTimestamp = currentTime + LocationLayerConstants.COMPASS_UPDATE_RATE_MS;
  } else if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
    internalCompassListener.onCompassChanged((event.values[0] + 360) % 360);
    for (CompassListener compassListener : compassListeners) {
      compassListener.onCompassChanged((event.values[0] + 360) % 360);
    }
  }
}
 
Example 22
Project: Taxi-Datalogger   File: DataLoggerActivity.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    switch (sensorEvent.sensor.getType()) {
        case Sensor.TYPE_AMBIENT_TEMPERATURE:
            mSensorData.temperature = sensorEvent.values[0];
            mSensorData.temperature_timestamp = sensorEvent.timestamp;
            break;
        case Sensor.TYPE_RELATIVE_HUMIDITY:
            mSensorData.humidity = sensorEvent.values[0];
            mSensorData.humidity_timestamp = sensorEvent.timestamp;
            break;
        case Sensor.TYPE_PRESSURE:
            mSensorData.pressure = sensorEvent.values[0];
            mSensorData.pressure_timestamp = sensorEvent.timestamp;
            break;
        case Sensor.TYPE_DEVICE_PRIVATE_BASE:
             if (HpmSensorDriver.SENSOR_STRING_TYPE.equals(sensorEvent.sensor.getStringType())) {
                mSensorData.pm25 = (int) sensorEvent.values[0];
                mSensorData.pm10 = (int) sensorEvent.values[1];
                mSensorData.particle_timestamp = sensorEvent.timestamp;
                break;
            }
        default:
            Log.w(TAG, "Unexpected sensor type: " + sensorEvent.sensor.getType());
    }
}
 
Example 23
Project: habpanelviewer   File: ProximityMonitor.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    float distance = event.values[0];

    Log.v("ProximityMonitor", "onSensorChanged" + distance);

    if (distance < mSensor.getMaximumRange()) {
        if (!mProximity) {
            mProximity = true;
            mServerConnection.updateState(mSensorItem, "CLOSED");
        }
    } else if (mProximity) {
        mProximity = false;
        mServerConnection.updateState(mSensorItem, "OPEN");
    }
}
 
Example 24
Project: AndroidSnooper   File: ShakeDetector.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
  float x = event.values[0];
  float y = event.values[1];
  float z = event.values[2];

  float gX = x / SensorManager.GRAVITY_EARTH;
  float gY = y / SensorManager.GRAVITY_EARTH;
  float gZ = z / SensorManager.GRAVITY_EARTH;

  // gForce will be close to 1 when there is no movement.
  float gForce = (float) Math.sqrt(gX * gX + gY * gY + gZ * gZ);

  if (gForce > SHAKE_THRESHOLD_GRAVITY) {
    final long now = System.currentTimeMillis();
    // ignore shake events too close to each other (500ms)
    if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
      return;
    }
    mShakeTimestamp = now;
    this.onShakeListener.onShake();
  }
}
 
Example 25
Project: CustomAndroidOneSheeld   File: PressureShield.java   View source code 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    if (flag && (oldInput != event.values[0] || isFirstTime)) {
        isFirstTime = false;
        frame = new ShieldFrame(UIShield.PRESSURE_SHIELD.getId(),
                PRESSURE_VALUE);
        oldInput = event.values[0];
        // frame.addByteArgument((byte) Math.round(event.values[0]));
        frame.addArgument(2, Math.round(event.values[0]));
        sendShieldFrame(frame);
        Log.d("Sensor Data of X", event.values[0] + "");
        if (eventHandler != null)
            eventHandler.onSensorValueChangedFloat(event.values[0] + "");
        //
        flag = false;
    }

}
 
Example 26
Project: smart-asset-iot-android-demo   File: ShakeDetector.java   View source code 5 votes vote down vote up
/**
 * Returns true if the device is currently accelerating.
 */
private boolean isAccelerating(SensorEvent event) {
    float ax = event.values[0];
    float ay = event.values[1];
    float az = event.values[2];

    // Instead of comparing magnitude to ACCELERATION_THRESHOLD,
    // compare their squares. This is equivalent and doesn't need the
    // actual magnitude, which would be computed using (expensive) Math.sqrt().
    final double magnitudeSquared = ax * ax + ay * ay + az * az;
    return magnitudeSquared > accelerationThreshold * accelerationThreshold;
}
 
Example 27
Project: homescreenarcade   File: GameActivity.java   View source code 5 votes vote down vote up
public void onSensorChanged(SensorEvent event) {
	
	try {
		Thread.sleep(16);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	xAccel = event.values[0];
	yAccel = event.values[1];
	//float z = event.values[2];
	
	if(yAccel < 2.8F ){ // tilt up
		gameEngine.setInputDir(UP);
		//gameView.setDir(1);
	}
	if(yAccel > 7.5F ){ // tilt down
		gameEngine.setInputDir(DOWN);
		//gameView.setDir(2);
	}
	if (xAccel < -1.8F ) { // tilt to
																// right
		gameEngine.setInputDir(RIGHT);
		//gameView.setDir(3);
	}
	if (xAccel > 1.8F ) { // tilt to
																// left
		gameEngine.setInputDir(LEFT);
		//gameView.setDir(4);
	}

}
 
Example 28
Project: AC2RD   File: ShakeDetector.java   View source code 5 votes vote down vote up
public void onSensorChanged(SensorEvent sensorEvent)
{	
	try
	{
		if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
		{
			float xAxis = sensorEvent.values[0];
			float yAxis = sensorEvent.values[1];
			float zAxis = sensorEvent.values[2];
			
			previousAcceleration = currentAcceleration;
			currentAcceleration = (float) Math.sqrt((double) ((xAxis * xAxis) + (yAxis * yAxis) + (zAxis * zAxis)));
			
			float accelerationDelta = currentAcceleration - previousAcceleration;
			acceleration = acceleration * 0.9f + accelerationDelta;
	
			if (acceleration > shakeDetectorThreshold)
			{
				int callDirection = shakeDetectorServiceManager.getCallDirection(shakeDetectorContext);
				String telephoneNumber = shakeDetectorServiceManager.getTelephoneNumber(shakeDetectorContext);

				RecordServiceManager recordServiceManager = new RecordServiceManager();
				recordServiceManager.startService(shakeDetectorContext.getApplicationContext(), callDirection, telephoneNumber);

				shakeDetectorServiceManager.stopService(shakeDetectorContext);
	    	}
		}
	}
	catch (Exception e)
	{
		Log.e("ShakeDetector", "SensorEventListener : " + shakeDetectorContext.getString(R.string.log_shake_detector_error_sensor_event_listener) + " : " + e);
		databaseManager.insertLog(shakeDetectorContext, "" + shakeDetectorContext.getString(R.string.log_shake_detector_error_sensor_event_listener), new Date().getTime(), 1, false);
	}
}
 
Example 29
Project: appinventor-extensions   File: GyroscopeSensor.java   View source code 5 votes vote down vote up
/**
 * Responds to changes in the gyroscope sensors.
 *
 * @param sensorEvent an event from the gyroscope sensor
 */
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
  if (enabled) {

    xAngularVelocity = (float) Math.toDegrees(sensorEvent.values[0]);
    yAngularVelocity = (float) Math.toDegrees(sensorEvent.values[1]);
    zAngularVelocity = (float) Math.toDegrees(sensorEvent.values[2]);

    // Raise event.
    GyroscopeChanged(xAngularVelocity, yAngularVelocity, zAngularVelocity,
        sensorEvent.timestamp);
  }
}
 
Example 30
Project: nirbhaya   File: PhoneLocatorService.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    Sensor mySensor = event.sensor;
    float x = 0;
    float y = 0;
    float z = 0;

    if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        x = event.values[0];
        y = event.values[1];
        z = event.values[2];
    }


    if ((Math.sqrt(x*x + y*y + z*z) < FREEFALL_THRESHOLD) && !firstTimeAlert){



        if(am.isMicrophoneMute()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    am.adjustStreamVolume(AudioManager.STREAM_ALARM, AudioManager.ADJUST_UNMUTE, 0);
            }
            else {
                // Note that this must be the same instance of audioManager that mutes
                // http://stackoverflow.com/questions/7908962/setstreammute-never-unmutes?rq=1
                am.setStreamMute(AudioManager.STREAM_ALARM, false);
            }
        }

        mediaPlayer.setLooping(true);
        mediaPlayer.start();
        firstTimeAlert = true;
        mediaPlayerOncePlayed = true;

        this.startService(mLocationSendServiceIntent);
    }
}
 
Example 31
Project: HealthOMeter   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        simpleStepDetector.updateAccel(
                event.timestamp, event.values[0], event.values[1], event.values[2]);
    }
}
 
Example 32
Project: MegviiFacepp-Android-SDK   File: SensorEventUtil.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
	final double G = 9.81;
	final double SQRT2 = 1.414213;
	if (event.sensor == null) {
		return;
	}

	if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		if (z >= G / SQRT2) { //screen is more likely lying on the table
			if (x >= G / 2) {
				orientation = 1;
			} else if (x <= -G / 2) {
				orientation = 2;
			} else if (y <= -G / 2) {
				orientation = 3;
			} else {
				orientation = 0;
			}
		} else {
			if (x >= G / SQRT2) {
				orientation = 1;
			} else if (x <= -G / SQRT2) {
				orientation = 2;
			} else if (y <= -G / SQRT2) {
				orientation = 3;
			} else {
				orientation = 0;
			}
		}
	}
}
 
Example 33
Project: DailyStudy   File: SensorActivity.java   View source code 5 votes vote down vote up
@Override
        public void onSensorChanged(SensorEvent event) {
//            Logger.e(TAG, "onSensorChanged");
            textView1.setText(String.format("X轴加速度:%1$s", event.values[0]));
            textView2.setText(String.format("Y轴加速度:%1$s", event.values[1]));
            textView3.setText(String.format("Z轴加速度:%1$s", event.values[2]));
        }
 
Example 34
Project: ActivityMonitor   File: RecorderService.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    long ts = event.timestamp;
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
    String row = String.format("%d,%f,%f,%f\n", ts, x, y, z);
    storage.append(row);
}
 
Example 35
Project: ToDay   File: ShakeSensor.java   View source code 5 votes vote down vote up
private float calcMaxAcceleration(SensorEvent event) {
    gravity[0] = calcGravityForce(event.values[0], 0);
    gravity[1] = calcGravityForce(event.values[1], 1);
    gravity[2] = calcGravityForce(event.values[2], 2);

    float accX = event.values[0] - gravity[0];
    float accY = event.values[1] - gravity[1];
    float accZ = event.values[2] - gravity[2];

    float max1 = Math.max(accX, accY);
    return Math.max(max1, accZ);
}
 
Example 36
Project: phonk   File: PMagnetic.java   View source code 5 votes vote down vote up
@ProtoMethod(description = "Start the magnetic sensor", example = "")
@ProtoMethodParam(params = {"function(value)"})
public void start() {
    super.start();

    mListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            ReturnObject r = new ReturnObject();
            r.put("x", event.values[0]);
            r.put("y", event.values[1]);
            r.put("z", event.values[2]);
            mCallbackMagneticChange.event(r);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            switch (accuracy) {
                case SensorManager.SENSOR_STATUS_UNRELIABLE:
                    break;
                case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
                    break;
                case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
                    break;
                case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
                    break;
            }
        }

    };

    isEnabled = mSensormanager.registerListener(mListener, sensor, speed);
}
 
Example 37
Project: boohee_v5.6   File: StepCounterService.java   View source code 5 votes vote down vote up
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == 19) {
        if (event.values[0] >= ((float) this.MAX_VALUE) || event.values[0] < 0.0f) {
            this.isError = true;
            return;
        }
        this.isError = false;
        int count = (int) event.values[0];
        if (this.lastSteps < 0) {
            this.lastSteps = 0;
        }
        if (this.lastSensorSteps > 0 && count > this.lastSensorSteps && this.shouldAddDx) {
            int countx = count - this.lastSensorSteps;
            if (countx > 20000) {
                this.isError = true;
                return;
            }
            this.totalSteps += countx;
            this.isError = false;
            this.lastSensorSteps = 0;
            this.shouldAddDx = false;
        }
        addSteps(count);
    } else if (event.sensor.getType() == 18) {
        addSteps(this.lastSteps + 1);
    }
}
 
Example 38
Project: letv   File: LetvSensorEventListener.java   View source code 5 votes vote down vote up
public void onSensorChanged(SensorEvent event) {
    if (!this.isStop && !this.isLive && PreferencesManager.getInstance().isShack() && this.context != null) {
        int sensorType = event.sensor.getType();
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (sensorType == 1 && Math.abs(x) > ((float) 16) && Math.abs(y) > ((float) 14) && Math.abs(z) > ((float) 17)) {
            this.sm.unregisterListener(LetvApplication.getInstance().getLetvSensorEventListener());
            LogInfo.log("zhuqiao", "...onSensorChanged...1");
            AMapLocation location = AMapLocationTool.getInstance().location();
            LogInfo.log("zhuqiao", "...onSensorChanged...isRun=" + this.isRun);
            if (!this.isRun && location != null) {
                this.isRun = true;
                this.isStop = true;
                LogInfo.log("zhuqiao", "from =" + this.from);
                if (!TextUtils.equals(this.from, "AlbumPlayActivity") || this.flow == null) {
                    LogInfo.log("zhuqiao", "context =" + this.context);
                    new LetvRequest().setUrl(LetvUrlMaker.getShakeCommitUrl(DataUtils.generateDeviceId(this.context), location.getLongitude() + "", location.getLatitude() + "")).setRequestType(RequestManner.NETWORK_ONLY).setCache(new VolleyNoCache()).setParser(new ShackCommitParser()).setCallback(new 3(this)).add();
                    return;
                }
                ShackVideoInfoBean videoInfo = this.flow.getShackVideoInfo();
                LogInfo.log("zhuqiao", "...onSensorChanged...videoInfo=" + videoInfo);
                if (videoInfo != null) {
                    new LetvRequest().setUrl(LetvUrlMaker.getShakeSubmitUrl(videoInfo.aid + "", videoInfo.vid + "", DataUtils.generateDeviceId(this.context), videoInfo.playtime + "", (videoInfo.aid != 0 ? 1 : 3) + "", location.getLongitude() + "", location.getLatitude() + "")).setCache(new VolleyNoCache()).setRequestType(RequestManner.NETWORK_ONLY).setParser(new 2(this)).setCallback(new 1(this)).add();
                }
            } else if (PreferencesManager.getInstance().isShack()) {
                this.sm.registerListener(LetvApplication.getInstance().getLetvSensorEventListener(), this.mSensor, 1);
            }
        }
    }
}
 
Example 39
Project: PhoneFoneFun   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.values[0] == 0) {
        startConvo();
    } else {
        stopConvo();
    }
}
 
Example 40
Project: ros2_android   File: ProximitySensorAdapter.java   View source code 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    if(sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        synchronized (this.mutex) {
            this.proximity = sensorEvent.values[0];

            logger.debug("Sensor proximity value : " + this.proximity);
            System.out.println("Sensor proximity value : " + this.proximity);
        }
    }
}