I have come across a problem where the orientation sensorPortrait
does not work, i have tried enabling both through the manifest and within the activity itself with
As a work around i have created a SensorPortraitActivity
:
public class SensorPortraitActivity extends AppCompatActivity {
private static final int PORTRAIT = 0;
private static final int REVERSE_PORTRAIT = 180;
private static final int OFFSET = 45;
private static final int UNKNOWN = -1;
// account for 0 = 360 (eg. -1 = 359)
private static final int PORTRAIT_START = PORTRAIT - OFFSET + 360;
private static final int PORTRAIT_END = PORTRAIT + OFFSET;
private static final int REVERSE_PORTRAIT_START = REVERSE_PORTRAIT - OFFSET;
private static final int REVERSE_PORTRAIT_END = REVERSE_PORTRAIT + OFFSET;
private OrientationChangeListener mListener;
private OrientationEventListener mOrientationListener;
private CurrentOrientation mCurrentOrientation;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mOrientationListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int i) {
orientationChanged(i);
}
};
}
@Override
protected void onResume() {
super.onResume();
mOrientationListener.enable();
}
@Override
protected void onPause() {
super.onPause();
mOrientationListener.disable();
}
//optional
public void setOrientationChangeListener(OrientationChangeListener listener){
mListener = listener;
}
private void orientationChanged(int degrees) {
if (degrees != UNKNOWN){
if (degrees >= PORTRAIT_START || degrees <= PORTRAIT_END){
if (mCurrentOrientation != CurrentOrientation.PORTRAIT){
mCurrentOrientation = CurrentOrientation.PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (mListener != null){
mListener.onPortrait();
}
}
} else if (degrees >= REVERSE_PORTRAIT_START && degrees <= REVERSE_PORTRAIT_END){
if (mCurrentOrientation != CurrentOrientation.REVERSE_PORTRAIT){
mCurrentOrientation = CurrentOrientation.REVERSE_PORTRAIT;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
if (mListener != null) {
mListener.onReversePortrait();
}
}
}
}
}
interface OrientationChangeListener {
void onPortrait();
void onReversePortrait();
}
enum CurrentOrientation {
PORTRAIT, REVERSE_PORTRAIT
}
}
Although it does seem like overkill for something as simple as this.
To use it simple extend SensorPortraitActivity
public class ExampleActivity extends SensorPortraitActivity implements SensorPortraitView.OrientationChangeListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set listener if you want callbacks
super.setOrientationChangeListener(this);
}
@Override
public void onPortrait() {
//portrait orientation
}
@Override
public void onReversePortrait() {
//reverse portrait orientation
}
}