1

I am trying to implement the logic for finding the qibla direction.

I used Sensor.TYPE_ORIENTATION and copied the code from here

mSensorManager =  (SensorManager) context.getSystemService(SENSOR_SERVICE);
sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

but I found that the Sensor.TYPE_ORIENTATION is deprecated and instead, I used accelerometer and magnetic field sensors from here

here is my code now

private void registerSensor() {
        mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        magnetometer = mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mySensorManager.registerListener(mySensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
        mySensorManager.registerListener(mySensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);
    }
private SensorEventListener mySensorEventListener = new SensorEventListener() {
        float degree;
        float head;
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            if (lastKnownLocation == null || image == null || arrow == null) {
                return;
            }

            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
                mGravity = event.values;
            if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
                mGeomagnetic = event.values;
            if (mGravity != null && mGeomagnetic != null) {
                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);
                    degree = orientation[2]; // orientation contains: azimut, pitch and roll
                    head = orientation[0];
                }
            }

I am trying to get the degree and head. what am I doing wrong here?

Remon Shehatta
  • 906
  • 6
  • 16

0 Answers0