问题
I am trying to get the phone angles by using TYPE_ACCELEROMETER sensor. My goal is to get the angle values only after the phone is tilted. It works, but the problem is when I put my phone facing up on the table, it still says isLandscape = true;
private boolean isLandscape;
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER),1000000);
private final SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent mSensorEvent) {
float X_Axis = mSensorEvent.values[0];
float Y_Axis = mSensorEvent.values[1];
double angle = Math.atan2(X_Axis, Y_Axis)/(Math.PI/180);
if(!isLandscape) {
if(angle > 80) {
Orientation = 90;
isLandscape = true;
}
}
else
{
if(Math.abs(angle) < 10) {
Orientation = 0; //portrait
isLandscape = false;
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
What's the best way to get the phone angles only after the phone is tilted? I am sorry for bad English,
Thank you.
回答1:
I don't know if i understand your question ,but i think you want your app to calculate the angel of tilt only if the phone is in portrait ,first you need to take the value of mSensorEvent.values[0]
and in this case if the phone in stand state in will return 0
, tilt to right will be negative values from 1 to 9 ,and the left positive .
then you have to do all this just in case of mSensorEvent.values[1]
values between 9 and 7 for example (9 is perfect stand) . to ensure the the device in portrait position .
and if you need the degree angle values you can multiply the float value of mSensorEvent.values
by 10.
i hope this help you
UPDATE***
you can try this :
private boolean isLandscape;
@Override
public void onSensorChanged(SensorEvent mSensorEvent) {
float X_Axis = mSensorEvent.values[0];
float Y_Axis = mSensorEvent.values[1];
if((X_Axis <= 6 && X_Axis >= -6) && Y_Axis > 5){
isLandscape = false;
}
else if(X_Axis >= 6 || X_Axis <= -6){
isLandscape = true;
}
}
回答2:
Instead of register for ACCELEROMETER
sensor, just have a class member of type OrientationEventListener
. When the device is flat you should get OrientationEventListener.ORIENTATION_UNKNOWN
.
See Android landscape right to landscape left event for how create a OrientationEventListener
class member.
Or you can leave your code as is but also checking the device inclination. If the device is flat then set isLandscape
flag to whatever appropriate for your case. For how to calculate the device inclination see How to measure the tilt of the phone in XY plane using accelerometer in Android
来源:https://stackoverflow.com/questions/31361328/how-do-i-get-the-angle-degree-of-the-phone-with-sensor-s