onSensorChanged Google Map Rotate

2019-07-26 02:03发布

问题:

there is something bug to onSensorChange , I was able to move my map from facing north, my code was correct but its always rotate even the phone not moving

 @Override
    protected void onResume() {
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_STATUS_ACCURACY_LOW);
        mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_STATUS_ACCURACY_LOW);
    }
    @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) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
                SensorManager.getOrientation(mR, mOrientation);
                float azimuthInRadians = mOrientation[0];
                float azimuthInDegress = (float)(Math.toDegrees(azimuthInRadians)+360)%360;
                RotateAnimation ra = new RotateAnimation(
                mCurrentDegree,
                -azimuthInDegress,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);

                updateCamera(azimuthInDegress);
                }
            }, 3000);

        }

    }


    private void updateCamera(final Float bearing) {

        CameraPosition pos = CameraPosition.builder().target(latLng).zoom(20).bearing(bearing).build();
        mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));


    }

I already put delay 5 seconds time but its not working, Please help me thanks