I know that I have to use the class OrientationListener to get the angle from the device. I want to get the angle between -90° and 90°. I don't know how to do it. picture on the left: 90 degree, picture in the middle: 0 degree and picture on the right: -90 degree
Code
class OrientationListener implements SensorEventListener
{
@Override
public void onSensorChanged(SensorEvent event)
{
angle = Math.round(event.values[2]);
if (angle < 0)
{
angle = angle * -1;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
You can use this code for simple 0, 90, 180 degrees.
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
Surface.ROTATION_0 is 0 degrees, Surface,ROTATION_90 is 90 degrees etc.
You can also use SensorEventListener interface if you want the degrees other than 0, 90, etc:
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float rawX = event.values[0];
}
}
You'd need to get use this code to get the degrees:
double k = 90/9.8;
double degrees = rawX * k; // this is a rough estimate of degrees, converted from gravity
This is a working example.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
String rotString="";
switch(rotation) {
case Surface.ROTATION_0:
rotString="portrait";
break;
case Surface.ROTATION_90:
rotString="landscape left";
break;
case Surface.ROTATION_180:
rotString="flipped portrait";
break;
case Surface.ROTATION_270:
rotString="landscape right";
break;
}
tv.setText(rotString);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With