Ok, after trying to use the Android API and not being able to do what I need, I implemented my own algorithm and actually it wasn’t that complicated:
I used a OrientationEventListener, and calculated if the orientation is in the 4 orientation points (in my code I only detect LANDSCAPE_RIGHT
and PORTRAIT_UP
:
orientationListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) {
public void onOrientationChanged(int orientation) {
if(canShow(orientation)){
show();
} else if(canDismiss(orientation)){
dismiss();
}
}
};
@Override
public void onResume(){
super.onResume();
orientationListener.enable();
}
@Override
public void onPause(){
super.onPause();
orientationListener.disable();
}
private boolean isLandscape(int orientation){
return orientation >= (90 - THRESHOLD) && orientation <= (90 + THRESHOLD);
}
private boolean isPortrait(int orientation){
return (orientation >= (360 - THRESHOLD) && orientation <= 360) || (orientation >= 0 && orientation <= THRESHOLD);
}
public boolean canShow(int orientation){
return !visible && isLandscape(orientation);
}
public boolean canDismiss(int orientation){
return visible && !dismissing && isPortrait(orientation);
}