Java Code Examples for android.hardware.SensorManager#getOrientation()

The following examples show how to use android.hardware.SensorManager#getOrientation() . 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: MagneticCompass.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onRotationUpdate(@NonNull float[] newMatrix) {
    // remap matrix values according to display rotation, as in
    // SensorManager documentation.
    switch (mDisplayRotation) {
        case Surface.ROTATION_90:
            SensorManager.remapCoordinateSystem(newMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, newMatrix);
            break;
        case Surface.ROTATION_270:
            SensorManager.remapCoordinateSystem(newMatrix, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_X, newMatrix);
            break;
        default:
            break;
    }
    mRotationMatrix.set(newMatrix);

    float[] deviceOrientation = new float[3];
    mOrientationCalculator.getOrientation(mRotationMatrix, mDisplayRotation, deviceOrientation);

    float[] orientation = new float[3];
    SensorManager.getOrientation(newMatrix, orientation);
    mFrag2D.setAngle((int) Math.toDegrees(orientation[0]));
}
 
Example 2
Source File: OrientationData.java    From tilt-game-android with MIT License 6 votes vote down vote up
private void updateOrientation() {
		SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerationValues, this.mMagneticFieldValues);

		// TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons.
		switch (this.mDisplayRotation) {
			case Surface.ROTATION_0:
				/* Nothing. */
				break;
			case Surface.ROTATION_90:
				SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix);
				break;
//			case Surface.ROTATION_180:
//				SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
//				break;
//			case Surface.ROTATION_270:
//				SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
//				break;
		}

		final float[] values = this.mValues;
		SensorManager.getOrientation(this.mRotationMatrix, values);

		for (int i = values.length - 1; i >= 0; i--) {
			values[i] = values[i] * MathConstants.RAD_TO_DEG;
		}
	}
 
Example 3
Source File: DeviceSensor.java    From iot-starter-for-android with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Callback for processing data from the registered sensors. Accelerometer and magnetometer
 * data are used together to get orientation data.
 *
 * @param sensorEvent The event containing the sensor data values.
 */
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    Log.v(TAG, "onSensorChanged() entered");
    if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        Log.v(TAG, "Accelerometer -- x: " + sensorEvent.values[0] + " y: "
                + sensorEvent.values[1] + " z: " + sensorEvent.values[2]);
        G = sensorEvent.values;

    } else if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        Log.v(TAG, "Magnetometer -- x: " + sensorEvent.values[0] + " y: "
                + sensorEvent.values[1] + " z: " + sensorEvent.values[2]);
        M = sensorEvent.values;
    }
    if (G != null && M != null) {
        if (SensorManager.getRotationMatrix(R, I, G, M)) {
            float[] previousO = O.clone();
            O = SensorManager.getOrientation(R, O);
            yaw = O[0] - previousO[0];
            Log.v(TAG, "Orientation: azimuth: " + O[0] + " pitch: " + O[1] + " roll: " + O[2] + " yaw: " + yaw);
        }
    }
}
 
Example 4
Source File: MagneticCompass.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onRotationUpdate(@NonNull float[] newMatrix) {
    // remap matrix values according to display rotation, as in
    // SensorManager documentation.
    switch (mDisplayRotation) {
        case Surface.ROTATION_90:
            SensorManager.remapCoordinateSystem(newMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, newMatrix);
            break;
        case Surface.ROTATION_270:
            SensorManager.remapCoordinateSystem(newMatrix, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_X, newMatrix);
            break;
        default:
            break;
    }
    mRotationMatrix.set(newMatrix);

    float[] deviceOrientation = new float[3];
    mOrientationCalculator.getOrientation(mRotationMatrix, mDisplayRotation, deviceOrientation);

    float[] orientation = new float[3];
    SensorManager.getOrientation(newMatrix, orientation);
    mFrag2D.setAngle((int) Math.toDegrees(orientation[0]));
}
 
Example 5
Source File: OrientationManager.java    From PTVGlass with MIT License 6 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
        // Get the current heading from the sensor, then notify the listeners of the
        // change.
        SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
        SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X,
                SensorManager.AXIS_Z, mRotationMatrix);
        SensorManager.getOrientation(mRotationMatrix, mOrientation);

        // Store the pitch (used to display a message indicating that the user's head
        // angle is too steep to produce reliable results.
        mPitch = (float) Math.toDegrees(mOrientation[1]);

        // Convert the heading (which is relative to magnetic north) to one that is
        // relative to true north, using the user's current location to compute this.
        float magneticHeading = (float) Math.toDegrees(mOrientation[0]);
        mHeading = MathUtils.mod(computeTrueNorth(magneticHeading), 360.0f)
                - ARM_DISPLACEMENT_DEGREES;

        notifyOrientationChanged();
    }
}
 
Example 6
Source File: RotationAngleDetector.java    From sensey with Apache License 2.0 6 votes vote down vote up
@Override
protected void onSensorEvent(SensorEvent sensorEvent) {
    // Get rotation matrix
    float[] rotationMatrix = new float[16];
    SensorManager.getRotationMatrixFromVector(rotationMatrix, sensorEvent.values);

    // Remap coordinate system
    float[] remappedRotationMatrix = new float[16];
    SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z,
            remappedRotationMatrix);

    // Convert to orientations
    float[] orientations = new float[3];
    SensorManager.getOrientation(remappedRotationMatrix, orientations);

    // Convert values in radian to degrees
    for (int i = 0; i < 3; i++) {
        orientations[i] = (float) (Math.toDegrees(orientations[i]));
    }

    rotationAngleListener.onRotation(orientations[0], orientations[1], orientations[2]);
}
 
Example 7
Source File: GyroscopeController.java    From crazyflie-android-client with GNU General Public License v2.0 6 votes vote down vote up
private void update(float[] vectors) {
    int AMP_MAX = 50;
    int AMPLIFICATION = AMP_MAX / mControls.getGyroAmplification();
    float[] rotationMatrix = new float[9];
    SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);
    int worldAxisX = SensorManager.AXIS_X;
    int worldAxisY = SensorManager.AXIS_Y;
    float[] adjustedRotationMatrix = new float[9];
    SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisX, worldAxisY, adjustedRotationMatrix);
    float[] orientation = new float[3];
    SensorManager.getOrientation(adjustedRotationMatrix, orientation);
    float pitch = (orientation[2] * FROM_RADS_TO_DEGS * -1) / AMPLIFICATION;
    float roll = (orientation[1] * FROM_RADS_TO_DEGS) / AMPLIFICATION;
    mSensorRoll = roll;
    mSensorPitch = pitch;
    updateFlightData();
}
 
Example 8
Source File: OrientationListener.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
/**
 * SensorEventListener method called when sensor values are updated. Reads gravitational and
 * magnetic field information, and when both are available computes the orientation values
 * and calls the delegate with them.
 */
@Override public void onSensorChanged(SensorEvent event) {
    switch(event.sensor.getType()) {
    case Sensor.TYPE_MAGNETIC_FIELD:
        mags = event.values.clone();
        break;
    case Sensor.TYPE_ACCELEROMETER:
        accels = event.values.clone();
        break;
    }

    if (mags!=null && accels!=null) {
        SensorManager.getRotationMatrix(R, I, accels, mags);
        SensorManager.getOrientation(R, orientationValues);
        delegate.receivedOrientationValues(
                orientationValues[0], orientationValues[1], orientationValues[2]);
    }
}
 
Example 9
Source File: ControllerActivity.java    From Bluefruit_LE_Connect_Android with MIT License 6 votes vote down vote up
private void updateOrientation() {
    float[] lastAccelerometer = mSensorData[kSensorType_Accelerometer].values;
    float[] lastMagnetometer = mSensorData[kSensorType_Magnetometer].values;
    if (lastAccelerometer != null && lastMagnetometer != null) {
        SensorManager.getRotationMatrix(mRotation, null, lastAccelerometer, lastMagnetometer);
        SensorManager.getOrientation(mRotation, mOrientation);

        final boolean kUse4Components = true;
        if (kUse4Components) {
            SensorManager.getQuaternionFromVector(mQuaternion, mOrientation);
            // Quaternions in Android are stored as [w, x, y, z], so we change it to [x, y, z, w]
            float w = mQuaternion[0];
            mQuaternion[0] = mQuaternion[1];
            mQuaternion[1] = mQuaternion[2];
            mQuaternion[2] = mQuaternion[3];
            mQuaternion[3] = w;

            mSensorData[kSensorType_Quaternion].values = mQuaternion;
        } else {
            mSensorData[kSensorType_Quaternion].values = mOrientation;
        }
    }
}
 
Example 10
Source File: TurnGameActivity.java    From cloud-cup-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    SensorManager.getRotationMatrixFromVector(mRotationMatrix , event.values);
    SensorManager.getOrientation(mRotationMatrix, mOrientation);

    float zAngle = mOrientation[0];

    //Log.d(LOG_TAG, "Turn z: " + zAngle);

    if(originalAngle == 0) {
        originalAngle = zAngle;
    }

    if( !halfTurn && Math.abs(zAngle - backtoRange(originalAngle + Math.PI)) < ANGLE_SENSIBILITY ) {
        halfTurn = true;
        demiTurns++;
        sendTurnValues();
    }

    if( halfTurn && Math.abs(zAngle - originalAngle) < ANGLE_SENSIBILITY) {
        halfTurn = false;
        demiTurns++;
        ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(100);
        sendTurnValues();
    }

}
 
Example 11
Source File: DeviceOrientation.java    From ARCore-Location with MIT License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    // Get the device heading
    float degree = Math.round( event.values[0] );
    currentDegree = -degree;

    switch (event.sensor.getType()) {
        case Sensor.TYPE_MAGNETIC_FIELD:
            mags = event.values.clone();
            break;
        case Sensor.TYPE_ACCELEROMETER:
            accels = event.values.clone();
            break;
    }

    if (mags != null && accels != null) {
        gravity = new float[9];
        magnetic = new float[9];
        SensorManager.getRotationMatrix(gravity, magnetic, accels, mags);
        float[] outGravity = new float[9];
        SensorManager.remapCoordinateSystem(gravity, SensorManager.AXIS_X,SensorManager.AXIS_Z, outGravity);
        SensorManager.getOrientation(outGravity, values);

        azimuth = values[0] * 57.2957795f;
        pitch = values[1] * 57.2957795f;
        roll = values[2] * 57.2957795f;
        mags = null;
        accels = null;
    }
}
 
Example 12
Source File: Drawer.java    From meter with Apache License 2.0 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor == mAccelerometer) {
        System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
        mLastAccelerometerSet = true;
    } else if (event.sensor == mMagnetometer) {
        System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
        mLastMagnetometerSet = true;
    }
    if (mLastAccelerometerSet && mLastMagnetometerSet) {
        SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);

        try {
            mDisplay = ((WindowManager) ((WallpaperService) context).getApplication().getSystemService(Service.WINDOW_SERVICE))
                    .getDefaultDisplay();
        } catch (Exception ignored){}


        int rotation = Surface.ROTATION_0;
        if(mDisplay != null) {
            rotation = mDisplay.getRotation();
        }

        float[] mRremap = mR.clone();
        if(rotation == Surface.ROTATION_90){
            SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, mRremap);
        }
        if(rotation == Surface.ROTATION_270){
            SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_X, mRremap);
        }
        if(rotation == Surface.ROTATION_180){
            SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, mRremap);
        }

        SensorManager.getOrientation(mRremap, mOrientation);
    }
}
 
Example 13
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
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);
      Log.d(TAG, "Yaw: " + orientation[0]); // Yaw
      Log.d(TAG, "Pitch: " + orientation[1]); // Pitch
      Log.d(TAG, "Roll: " + orientation[2]); // Roll
    }

    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);
}
 
Example 14
Source File: HeadScrollView.java    From glass_snippets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
	float[] mat = new float[9],
			orientation = new float[3];

	if (mLastAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
		return;

	SensorManager.getRotationMatrixFromVector(mat, event.values);
	SensorManager.remapCoordinateSystem(mat, SensorManager.AXIS_X, SensorManager.AXIS_Z, mat);
	SensorManager.getOrientation(mat, orientation);

	float z = orientation[0], // see https://developers.google.com/glass/develop/gdk/location-sensors/index
	      x = orientation[1],
		  y = orientation[2];

	if (mStartX == 10)
		mStartX = x;

	float mEndX = mStartX - (getChildAt(0).getHeight() - getHeight() * 0.5F) / VELOCITY;

	int prior = getScrollY(),
	      pos = (int) ((mStartX - x) * VELOCITY);

	if (x < mStartX) mStartX = x;
	else if (x > mEndX) mStartX += x - mEndX;

	smoothScrollTo(0, pos);
}
 
Example 15
Source File: CompassTile.java    From GravityBox with Apache License 2.0 4 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    float[] values;
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        if (mAcceleration == null) {
            mAcceleration = event.values.clone();
        }
        values = mAcceleration;
    } else {
        // Magnetic field sensor
        if (mGeomagnetic == null) {
            mGeomagnetic = event.values.clone();
        }
        values = mGeomagnetic;
    }

    for (int i = 0; i < 3; i++) {
        values[i] = ALPHA * values[i] + (1 - ALPHA) * event.values[i];
    }

    if (!mActive || !mListeningSensors || mUpdatePending ||
            mAcceleration == null || mGeomagnetic == null) {
        // Nothing to do at this moment
        return;
    }

    if (mCount++ <= 10) {
        return;
    }

    mCount = 0;
    float R[] = new float[9];
    float I[] = new float[9];
    if (!SensorManager.getRotationMatrix(R, I, mAcceleration, mGeomagnetic)) {
        // Rotation matrix couldn't be calculated
        return;
    }

    // Get the current orientation
    float[] orientation = new float[3];
    SensorManager.getOrientation(R, orientation);

    // Convert azimuth to degrees
    mNewDegree = Float.valueOf((float) Math.toDegrees(orientation[0]));
    mNewDegree = (mNewDegree + 360) % 360;

    mUpdatePending = true;
    refreshState();
}
 
Example 16
Source File: SensorUtils.java    From Pano360 with MIT License 4 votes vote down vote up
public static void getOrientation(SensorEvent event,float[] output){
    //sensorRotationVectorToMatrix(event,oTmp);
    SensorManager.getRotationMatrixFromVector(oTmp, event.values);
    SensorManager.getOrientation(oTmp,output);
}
 
Example 17
Source File: CompassActivity.java    From MuslimMateAndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * override function return every change
 *
 * @param event Sensor changes
 */
@Override
public void onSensorChanged(SensorEvent event) {

    double startTime = System.currentTimeMillis();

    if (event.sensor == mAccelerometer) {
        mLastAccelerometer = event.values;
        mLastAccelerometerSet = true;
    } else if (event.sensor == mMagnetometer) {
        mLastMagnetometer = event.values;
        mLastMagnetometerSet = true;
    }
    if (mLastAccelerometerSet && mLastMagnetometerSet) {
        boolean success = SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
        SensorManager.getOrientation(mR, mOrientation);
        float azimuthInRadians = mOrientation[0];
        double azimuthInDegress = -(float) (Math.toDegrees(azimuthInRadians) + 360) % 360;

        if (Math.abs(azimuthInDegress - previousAzimuthInDegrees) > 300) {
            previousAzimuthInDegrees = azimuthInDegress;
        }

        azimuthInDegress = lowPass(azimuthInDegress, previousAzimuthInDegrees, startTime);

        if (mapReady) updateCamera((float) azimuthInDegress);

        RotateAnimation ra = new RotateAnimation(
                (float) previousAzimuthInDegrees,
                (float) azimuthInDegress,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);

        ra.setDuration(500);
        ra.setFillAfter(true);
        compass.startAnimation(ra);
        innerPosition.startAnimation(ra);

        previousAzimuthInDegrees = azimuthInDegress;


        if (pointerPosition == true) {
            pointerFirstPositionX = compassLevel.getX();
            pointerFirstPositionY = compassLevel.getY();
            smallCircleRadius = smallCircleLevel.getX();
            pointerPosition = false;
        }

        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(mR, orientation);
            double yaw = orientation[0] * 57.2957795f;
            double pitch = orientation[1] * 57.2957795f;
            double roll = orientation[2] * 57.2957795f;
            if (pitch > 90) pitch -= 180;
            if (pitch < -90) pitch += 180;
            if (roll > 90) roll -= 180;
            if (roll < -90) roll += 180;

            double time = System.currentTimeMillis();

            if (!start) {
                lastTime = time;
                lastRoll = roll;
                lastPitch = pitch;
            }
            start = true;


            double dt = (time - lastTime) / 1000.0;
            roll = lowPassPointerLevel(roll, lastRoll, dt);
            pitch = lowPassPointerLevel(pitch, lastPitch, dt);
            lastTime = time;
            lastRoll = roll;
            lastPitch = pitch;

            newX = (float) (pointerFirstPositionX + pointerFirstPositionX * roll / 90.0);
            newY = (float) (pointerFirstPositionY + pointerFirstPositionY * pitch / 90.0);

            compassLevel.setX(newX);
            compassLevel.setY(newY);

            if (smallCircleRadius / 3 < Math.sqrt((roll * roll) + (pitch * pitch))) {
                compassLevel.setImageResource(R.drawable.ic_error_pointer);
            } else {
                compassLevel.setImageResource(R.drawable.ic_level_pointer);
            }
        }


    }

}
 
Example 18
Source File: AeyriumSensorPlugin.java    From aeyrium-sensor with MIT License 4 votes vote down vote up
private void updateOrientation(float[] rotationVector, EventChannel.EventSink events) {
  float[] rotationMatrix = new float[9];
  SensorManager.getRotationMatrixFromVector(rotationMatrix, rotationVector);

  final int worldAxisForDeviceAxisX;
  final int worldAxisForDeviceAxisY;

  // Remap the axes as if the device screen was the instrument panel,
  // and adjust the rotation matrix for the device orientation.
  switch (mWindowManager.getDefaultDisplay().getRotation()) {
    case Surface.ROTATION_0:
    default:
      worldAxisForDeviceAxisX = SensorManager.AXIS_X;
      worldAxisForDeviceAxisY = SensorManager.AXIS_Z;
      break;
    case Surface.ROTATION_90:
      worldAxisForDeviceAxisX = SensorManager.AXIS_Z;
      worldAxisForDeviceAxisY = SensorManager.AXIS_MINUS_X;
      break;
    case Surface.ROTATION_180:
      worldAxisForDeviceAxisX = SensorManager.AXIS_MINUS_X;
      worldAxisForDeviceAxisY = SensorManager.AXIS_MINUS_Z;
      break;
    case Surface.ROTATION_270:
      worldAxisForDeviceAxisX = SensorManager.AXIS_MINUS_Z;
      worldAxisForDeviceAxisY = SensorManager.AXIS_X;
      break;
  }

  
  float[] adjustedRotationMatrix = new float[9];
  SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisForDeviceAxisX,
          worldAxisForDeviceAxisY, adjustedRotationMatrix);

  // Transform rotation matrix into azimuth/pitch/roll
  float[] orientation = new float[3];
  SensorManager.getOrientation(adjustedRotationMatrix, orientation);

  double pitch = - orientation[1];
  double roll = - orientation[2];
  double[] sensorValues = new double[2];
  sensorValues[0] = pitch;
  sensorValues[1] = roll;
  events.success(sensorValues);
}
 
Example 19
Source File: KaabaLocatorFragment.java    From PrayTime-Android with Apache License 2.0 4 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
  if (mLastLocation == null) {
    return;
  }
  SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
  SensorManager.getOrientation(mRotationMatrix, mValues);

  /*
  if (BuildConfig.DEBUG) {
    System.out.println("sensorChanged (" + Math.toDegrees(mValues[0]) + ", " + Math.toDegrees(mValues[1]) + ", " + Math.toDegrees(mValues[2]) + ")");
  }
  */

  float bearing = 0f;

  if (mMap != null) {
    bearing = Double.valueOf(mMap.getCameraPosition().bearing).floatValue();
  }

  // get the angle around the z-axis rotated
  float degree = Double.valueOf(Math.toDegrees(mValues[0])).floatValue();

  if (Math.round(bearing) == Math.round(degree)) {
    System.out.println("bearing and degrees are the same.");
    return;
  }

  if (BuildConfig.DEBUG) {
    System.out.println("degrees " + degree + ", bearing " + bearing);
  }

  //tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");

  CameraPosition cameraPosition = mMap.getCameraPosition();
  CameraPosition newPosition = new CameraPosition(cameraPosition.target, cameraPosition.zoom, cameraPosition.tilt, degree);
  mMap.moveCamera(CameraUpdateFactory.newCameraPosition(newPosition));
  // create a rotation animation (reverse turn degree degrees)
  /*
  RotateAnimation ra = new RotateAnimation(
          currentDegree,
          -degree-180,
          Animation.RELATIVE_TO_SELF, 0.5f,
          Animation.RELATIVE_TO_SELF,
          0.5f);

  // how long the animation will take place
  ra.setDuration(210);

  // set the animation after the end of the reservation status
  ra.setFillAfter(true);

  // Start the animation
  mCompass.startAnimation(ra);
  currentDegree = -degree-180;
  */
}
 
Example 20
Source File: CompassActivity.java    From coursera-android with MIT License 2 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {

    // Acquire accelerometer event data

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        mGravity = new float[3];
        System.arraycopy(event.values, 0, mGravity, 0, 3);

    }

    // Acquire magnetometer event data

    else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {

        mGeomagnetic = new float[3];
        System.arraycopy(event.values, 0, mGeomagnetic, 0, 3);

    }

    // If we have readings from both sensors then
    // use the readings to compute the device's orientation
    // and then update the display.

    if (mGravity != null && mGeomagnetic != null) {

        float rotationMatrix[] = new float[9];

        // Users the accelerometer and magnetometer readings
        // to compute the device's rotation with respect to
        // a real world coordinate system

        boolean success = SensorManager.getRotationMatrix(rotationMatrix,
                null, mGravity, mGeomagnetic);

        if (success) {

            float orientationMatrix[] = new float[3];

            // Returns the device's orientation given
            // the rotationMatrix

            SensorManager.getOrientation(rotationMatrix, orientationMatrix);

            // Get the rotation, measured in radians, around the Z-axis
            // Note: This assumes the device is held flat and parallel
            // to the ground

            float rotationInRadians = orientationMatrix[0];

            // Convert from radians to degrees
            mRotationInDegrees = Math.toDegrees(rotationInRadians);

            // Request redraw
            mCompassArrow.invalidate();

            // Reset sensor event data arrays
            mGravity = mGeomagnetic = null;

        }
    }

}