Skip to content

Instantly share code, notes, and snippets.

@423u5
Last active March 9, 2022 09:28
Show Gist options
  • Save 423u5/1fde7b70d2b661e51167034a26401941 to your computer and use it in GitHub Desktop.
Save 423u5/1fde7b70d2b661e51167034a26401941 to your computer and use it in GitHub Desktop.
Orientation track by sensor android
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
* @author Gopal chaudhary
* */
public class OrientationHandler {
private SensorManager sensorManager;
private OrientationListener listener;
public void trackOrientation (Context context, OrientationListener listener) {
this.listener = listener;
if (sensorManager == null)
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(_listener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
private final SensorEventListener _listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent == null || listener == null) return;
double x1 = Math.abs(sensorEvent.values[0]);
double x2 = Math.abs(sensorEvent.values[1]);
if (x1 > 5 || x2 > 5) {
listener.onChange(x1 > x2 ? ORIENTATION_LANDSCAPE : ORIENTATION_PORTRAIT);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
public void dispose() {
if (sensorManager != null)
sensorManager.unregisterListener(_listener);
}
}
public interface OrientationListener {
void onChange(int orientation);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment