Here is code which is intended to make my Android mobile phone vibrate when some condition is true. It should vibrate till azimuth angle (which I get from magnetometer) is not in a given range.

But no matter in which direction I point the phone, it never vibrates. It enters the if statement but never the while statement. And the vibrate function is working (i.e. the phone isn't broken). My purpose is to find north south east west.

What am I doing wrong?

public void onCreate(Bundle savedInstanceState) {
    // some code        
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){
        // Success! There's a magnetometer.
        Toast.makeText(
            getApplicationContext(),
            "Detecting magnetic field",
            Toast.LENGTH_LONG).show();
        speakOut("not Working");
    }
    else {
        Toast.makeText(
            getApplicationContext(),
            "not working",
            Toast.LENGTH_LONG).show();
        speakOut("not Working");
    }
    // some code that calls the function
}

some_function(){
    if (//some condition) {
        while (!(85 < azimuth_angle) && !(azimuth_angle < 95)) {
            viberator.vibrate(1000);
            //this should happen when it faces east.
        }
    } 
}

public void onSensorChanged(SensorEvent event) {
    // TODO: Auto-generated method stub
    azimuth_angle = event.values[0];
    pitch_angle = event.values[1];
    roll_angle = event.values[2];
}
有帮助吗?

解决方案

registerListener method is missing so your SensorEventListener wont't be triggered: http://developer.android.com/reference/android/hardware/SensorManager.html#registerListener(android.hardware.SensorEventListener, android.hardware.Sensor, int)

其他提示

Azimuth is not a compass direction. Here's some code I wrote for a compass sensor. It isn't 100% (it needs a much better filter on it, which I haven't had time or reason to write). But it shows the logic of getting the direction, you can work on filtering the return values better yourself.

Answer to previous question where I posted my code

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top