The sensor values are always relative to the default orientation, so you need to take account of the rotation away from the default orientation. To do this, use something like the following:
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
float screen_adjustment = 0;
switch(rotation) {
case Surface.ROTATION_0: screen_adjustment = 0; break;
case Surface.ROTATION_90: screen_adjustment = (float)Math.PI/2; break;
case Surface.ROTATION_180: screen_adjustment = (float)Math.PI; break;
case Surface.ROTATION_270: screen_adjustment = 3*(float)Math.PI/2; break;
}
to adjust the azimith. For a fully working example, see the code that I posted in my answer here.