That's not simple :)
to use the TYPE_MAGNETIC_FIELD you should know how the earth magnetic field is oriented at your location and it's not trivial.
You can try to use the TYPE_GRAVITY and TYPE_LINEAR_ACCELERATION: the first returns the gravity acceleration vector, the second the acceleration of the device excluding gravity (it should be something like LINEAR_ACCELERATION = ACCELEROMETER - GRAVITY, but i don't know how precise it is).
To have the gravity on the z axis you have to perform a rotation of the gravity vector to have it in the form (0 0 g)... Actually you have to find the rotation matrix that tranform your gravity vector in the form (0 0 g). More on this here (wikipedia).
Once you have this matrix you apply it to the linear acceleration vector and its x and y components will be the ones you are looking for.
If your phone doesn't have this two sensors, you have to calculate gravity and linear acceleration yourself: to do this you can implement an hig-pass filter to get the linear acceleration and a low pass filter to get the gravity vector. More on this here.