joon
joon

Reputation: 870

How to determine orientation through accelerometer?

I'm using Processing for Android and my app is almost finished. However, Processing for Android doesn't adapt to phone orientation, which I want to implement. It reads Accelerometer values and I've been able to roughly determine the orientation through this simple algorhitm:

  if (y > 7)
  {
    o = UPRIGHT;
  }
  else if (y < -7)
  {
    o = UPSIDEDOWN;
  }      
  else if (x > 7)
  {
    o = TURNLEFT;
  }
  else
  {
    o = TURNRIGHT;
  }   

It's not flawless, so I'm wondering if there's a better solution. Is there a way to poll Android for the current phone UI orientation? Is there a more stable value than 7 (which I chose kind of arbitrarily)?

Upvotes: 0

Views: 477

Answers (1)

t0mm13b
t0mm13b

Reputation: 34592

By monitoring for the following configuration change on orientation, based on the AndroidManifest.xml, for example, assuming that activity is called myActivity, then the following would suffice:

<activity android:name=".myActivity" 
    android:configChanges="orientation" 
    android:label="MyActivity" />

And from the myActivity class, handle it with this:

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
    switch(newConfig.orientation){
    case Configuration.ORIENTATION_UNDEFINED:
        Log.v(TAG, "[onConfigurationChanged] - Undefined");
        break;
    case Configuration.ORIENTATION_SQUARE:
        Log.v(TAG, "[onConfigurationChanged] - Square");
        break;
    case Configuration.ORIENTATION_PORTRAIT:
        Log.v(TAG, "[onConfigurationChanged] - Portrait");
        break;
    case Configuration.ORIENTATION_LANDSCAPE:
        Log.v(TAG, "[onConfigurationChanged] - Landscape");
        break;
    }
}

Upvotes: 2

Related Questions