Orientation
- The Phone Orientation
- By default the phone's orientation is detected by a sensor, and apps adapt to any change.
- You can specify in the application or activity element in the manifest
a fixed orientation, e.g., android:screenOrientation="landscape".
- If not using a fixed orientation, by default when there's a configuration change (e.g.,
the phone's orientation) Android restarts the activity (including calls to
onDestroy and onCreate).
- You can specify in the activity element in the manifest to listen for
orientation changes using android:screenOrientation="fullSensor".
There are other options too.
- You can specify in the activity which configuration changes the activity handles
itself, e.g., handling orientation changes is done with
android:configChanges="orientation|screenSize".
- If your app is handling orientation changes you must implement
onConfigurationChanged, and in that call super.onConfigurationChanged
before doing any app specific processing (there could be none).
- Obtaining Sensor Information
- Phones have various hardware sensors.
- The magnetic field sensor provides 3D information about the phone.
- The gravity sensor provides acceleration information in 3D.
- The proximity sensor senses your face (or somthing) near the phone.
- Many more, see the
Sensor
class.
- Get a SensorManager as a system service.
- Register a listener that implements the SensorEventListener interface.
- It's important to disable sensors when not in use, because they chew battery.
- Read the documentation for SensorManager and SensorEvent.
- Getting a compass bearing
- Confirm that there are sensors of the type Sensor.TYPE_MAGNETIC_FIELD and
Sensor.TYPE_ACCELEROMETER.
- Use the magnetic field and accelerometer values that are passed to the listener to
compute the orientation, which is an array of three floats:
- The 0th element provides azimuth, i.e., rotation around the Z-axis that
points to the center of the earth.
The value is a radian value -PI to PI, with 0 being magnetic north.
- The 1st element provides pitch, i.e., rotation around the X-axis that is
tangential to the earth and points roughly west.
The value is a radian value -PI to PI, with 0 being flat.
- The 2nd element provides roll, i.e., rotation around the Y-axis that is
tangential to the earth and points towards magnetic north.
The value is a radian value -PI to PI, with 0 being flat.
- In the emulator, remember to pitch the phone -90 to make it flat when trying to do
compass-style things with orientation.
- Example
MainActivity.java
activity_main.xml
strings.xml
dimens.xml
AndroidManifest.xml