Skip to content

Instantly share code, notes, and snippets.

@yudikarma
Last active January 11, 2019 09:41
Show Gist options
  • Save yudikarma/46239084f3d962cd98e6b601f3af0463 to your computer and use it in GitHub Desktop.
Save yudikarma/46239084f3d962cd98e6b601f3af0463 to your computer and use it in GitHub Desktop.
method detect reverse portrait
private SensorManager mSensorManager;
private Sensor mOrientation;
boolean Upsidedown = false;
float value_0 = -10000;
float value_1 = -10000;
float deviceRotation = 0.0f;
boolean ispotrait = false;
public float calcAng(float x, float y) {
if (y >= 0.0f) {
if (x < 0.0f) {
return (float) (180.0d - ((Math.atan((double) (y / (-x))) / 3.141592653589793d) * 180.0d));
}
if (x == 0.0f) {
return 90.0f;
}
return (float) ((Math.atan((double) (y / x)) / 3.141592653589793d) * 180.0d);
} else if (x < 0.0f) {
return (float) (((Math.atan((double) (y / x)) / 3.141592653589793d) * 180.0d) + 180.0d);
} else {
if (x == 0.0f) {
return 270.0f;
}
return (float) (360.0d - ((Math.atan((double) ((-y) / x)) / 3.141592653589793d) * 180.0d));
}
}
private SensorEventListener mOrientationSensorListener = new SensorEventListener() {
int orientation = -1;
@Override
public void onSensorChanged(SensorEvent event) {
float Theta = 0.0f;
float aX = event.values[0];
float aY = event.values[1];
float aZ = event.values[2];
float Rmag = (float) Math.sqrt((double) (((aX * aX) + (aY * aY)) + (aZ * aZ)));
if (Rmag > 0.0f) {
Theta = (float) ((Math.acos((double) (aZ / Rmag)) / 3.141592653589793d) * 180.0d);
}
float Phi = (90.0f + calcAng(aX, aY)) + deviceRotation;
while (Phi < 0.0f) {
Phi += 360.0f;
}
while (Phi > 360.0f) {
Phi -= 360.0f;
}
if ((Phi > 320.0f || Phi < 40.0f) && Theta > 45.0f && Theta < 135.0f) {
//revese portrait
//this.Upsidedown = true;
if (state.equalsIgnoreCase("is_playing")){
pauseCountDown();
beginCountUP();
}
} else {
//portrait
//this.Upsidedown = false;
if (state.equalsIgnoreCase("begin_countup_isplaying")){
cancelCountUp();
continueCountDown();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
how to use ?
// Get sensor manager
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// Get the default sensor of specified type
mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(mOrientationSensorListener, mOrientation,
SensorManager.SENSOR_DELAY_GAME);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment