This is actually much more difficult than you might suppose.
The phone's gyroscope sensors give you the movement of the phone with respect to the phone, not the world. Leaving the phone face-up, flat on the table would give you
x = 0.0
,
y = 0.0
,
z = -9.8
.
These values would be fluctuating slightly due to the sensors. As the phone rotates, these base (at rest) values change - at 45 degrees you get
x = 6.93
,
y = 0
,
z = 6.93
,
so that sqrt(x*x + y*y + z*z) = 9.8
. If you want to isolate up-down movement, you either have to stop the phone rotating, or ignore this movement.
If you stop the phone rotating - e.g. phone must be held upright in pocket, then you can just look at the x
component which will, at rest, read -9.81
and changes will show acceleration, less-negative or positive being in an upward direction, more-negative in a downward direction.
If you wish to ignore other movement (e.g. user only uses this for defined activities), then the absolute value will do. sqrt(x*x + y*y + z*z)
will give you 9.8
at rest and changes to that value will be due to acceleration of the device. A bit of maths later (brute-force numerical integration) and you can have speed or distance travelled (although note that this get very inaccurate very quickly...)
Note there is a Rotation Vector Sensor API that may allow you to remove the device's orientation from the gyroscope readings allowing you to calculate the real-world movement, however I haven't tried this API and do not know what extra hardware (if any) is needed.