There is a weight sensor which senses if the plane is on the ground. This sensor prevents gear retraction while the plane is still on the ground. Failure of this sensor would prevent gear retraction after takeoff.
If you note closely, the landing gears (even the non-retractable ones) are not connected using a simple metal pole; rather, there is an oleo strut which is compressed by the weight of the aircraft. Besides airborne / ground detection, the struts absorb the vertical energy during touchdown.

I recall some decades ago engineers experimented obtaining the plane's gross weight by installing weight scales to each landing gear (as opposed to just an air/ground detection). The readings were found to be inaccurate and they soon abandoned the idea.
Landing gear stories cannot be complete without mentioning this incident in 1990:
A training captain of a Saab 340 was betting with his students that the weight-on-gear mechanism would prevent gear retraction while on the ground. On the accident airplane type, the mechanism would lock the gear handle, but the lock can be overridden if the pilot manually pull out and move the handle. The instructor confidently pulled out the handle and to his surprise, the hydraulics started to move and the gears were retracted while the plane was still on the ground.

(image source)
The aircraft was written off. This incompetent instructor pilot was killed 11 years later in another accident.