سؤال

I am writing an compass application but can't access the sensors needed for some reason. I have implemented the SensorEventListener interface and register my sensors this way:

    sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

In my onSensorChange() method:

public void onSensorChanged(SensorEvent event) {
    Toast t = Toast.makeText(this, "onSensorChanged", Toast.LENGTH_LONG);
    t.setGravity(Gravity.TOP, 0, 0);
    t.show();
    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);
            north = orientation[0];
        }
    }
}

The Toast message won't show on the screen and when I try to put the north value in a TextView the output is 0. Would be great if someone could explain to me why I can't access the onSensorChanged() method. Permissions in manifest:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
هل كانت مفيدة؟

المحلول

sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);

Do not forget to unregister them.

More: http://developer.android.com/reference/android/hardware/SensorManager.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top