Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the angle/degree of the phone with sensor/s?

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.

like image 505
IYM-14 Avatar asked Jul 11 '15 20:07

IYM-14


1 Answers

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;
        }

    } 
like image 168
Khalil Tam Avatar answered Sep 21 '22 10:09

Khalil Tam