Last active
March 9, 2022 09:28
-
-
Save 423u5/1fde7b70d2b661e51167034a26401941 to your computer and use it in GitHub Desktop.
Orientation track by sensor android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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