Modern Android devices include GPS chips, cameras, and motion sensors. Apps access them through Android APIs with appropriate runtime permissions and battery-conscious patterns.
GPS (Global Positioning System) uses satellite signals to determine latitude, longitude, altitude, and accuracy. Android exposes location through the LocationManager and the higher-level Fused Location Provider.
Manifest permissions
XML — AndroidManifest.xml<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Background location (only if needed — requires extra approval) -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
LocationManager (legacy approach)
Kotlin — Basic GPS via LocationManager@SuppressLint("MissingPermission")
fun getLastKnownGpsLocation(context: Context): Location? {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
if (!isGpsEnabled) {
Log.w("GPS", "GPS provider is disabled")
return null
}
return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
}
@SuppressLint("MissingPermission")
fun requestGpsUpdates(context: Context, callback: (Location) -> Unit) {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val listener = LocationListener { location -> callback(location) }
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
5000L, // min time ms
10f, // min distance meters
listener
)
}
Location object properties
Property
Description
latitude / longitude
Coordinates in decimal degrees
accuracy
Radius of uncertainty in meters
altitude
Height above sea level (if available)
speed
Ground speed in m/s
time
UTC timestamp of fix
2Fused Location Provider
The Fused Location Provider (Google Play Services) intelligently combines GPS, Wi-Fi, and cell towers for accurate, battery-efficient location. It is the recommended approach for most apps.
SensorManager gives access to device hardware sensors — accelerometer, gyroscope, light, proximity, and more. Register listeners in onResume and unregister in onPause to save battery.
Basic sensor setup
Kotlin — SensorActivity.ktclass SensorActivity : AppCompatActivity(), SensorEventListener {
private lateinit var sensorManager: SensorManager
private var accelerometer: Sensor? = null
private var gyroscope: Sensor? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sensor)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
if (accelerometer == null) {
Toast.makeText(this, "No accelerometer on this device", Toast.LENGTH_SHORT).show()
}
}
override fun onResume() {
super.onResume()
accelerometer?.let {
sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI)
}
gyroscope?.let {
sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onPause() {
super.onPause()
sensorManager.unregisterListener(this)
}
override fun onSensorChanged(event: SensorEvent?) {
event ?: return
when (event.sensor.type) {
Sensor.TYPE_ACCELEROMETER -> handleAccelerometer(event.values)
Sensor.TYPE_GYROSCOPE -> handleGyroscope(event.values)
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
}
Sensor delay constants
Constant
Rate
Use Case
SENSOR_DELAY_FASTEST
~0 ms (max rate)
Games, high-frequency apps
SENSOR_DELAY_GAME
~20 ms
Interactive games
SENSOR_DELAY_UI
~60 ms
UI animations, shake detection
SENSOR_DELAY_NORMAL
~200 ms
Screen rotation, step counter
6Accelerometer
The accelerometer measures acceleration forces on the device across three axes (X, Y, Z) in m/s². Uses include shake detection, step counting, tilt controls, and screen orientation.
Read accelerometer values
Kotlin — Display X, Y, Z valuesprivate fun handleAccelerometer(values: FloatArray) {
val x = values[0]
val y = values[1]
val z = values[2]
binding.tvAccel.text = String.format(
Locale.getDefault(),
"Accel — X: %.2f Y: %.2f Z: %.2f m/s²", x, y, z
)
}
Shake detection
Kotlin — Detect device shakeclass ShakeDetector(private val onShake: () -> Unit) : SensorEventListener {
private var lastUpdate = 0L
private var lastX = 0f
private var lastY = 0f
private var lastZ = 0f
private val shakeThreshold = 800f
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor.type != Sensor.TYPE_ACCELEROMETER) return
val currentTime = System.currentTimeMillis()
if (currentTime - lastUpdate > 100) {
val diffTime = currentTime - lastUpdate
lastUpdate = currentTime
val x = event.values[0]
val y = event.values[1]
val z = event.values[2]
val speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000
if (speed > shakeThreshold) onShake()
lastX = x; lastY = y; lastZ = z
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
}
Axis orientation
Phone held upright (portrait):
X → right edge
Y → top edge
Z → out of screen (toward user)
Flat on table: Z ≈ 9.8 m/s² (gravity)
Free fall: all axes ≈ 0
7Gyroscope
The gyroscope measures angular rotation rate around X, Y, and Z axes in radians per second. It detects how fast the device is spinning — essential for AR, games, and camera stabilization.
Read gyroscope values
Kotlin — Display rotation ratesprivate fun handleGyroscope(values: FloatArray) {
val x = values[0] // pitch rate
val y = values[1] // yaw rate
val z = values[2] // roll rate
binding.tvGyro.text = String.format(
Locale.getDefault(),
"Gyro — X: %.3f Y: %.3f Z: %.3f rad/s", x, y, z
)
}
Best practice: Always unregister sensor listeners in onPause(). Use the lowest sensor delay that meets your needs. Combine accelerometer + gyroscope with a sensor fusion algorithm (or Sensor.TYPE_ROTATION_VECTOR) for smooth orientation tracking.
8Hands-On Exercises
1
Request location permission and display the device's last known GPS coordinates in a TextView using LocationManager.
2
Refactor to the Fused Location Provider with continuous updates. Show latitude, longitude, and accuracy updating every 5 seconds.
3
Build a CameraX preview screen with a live camera feed using PreviewView.
4
Add a capture button that saves a photo to app-specific external storage and shows a thumbnail.
5
Implement profile photo pick using the system TakePicture contract with FileProvider.
6
Register SensorManager listeners and display live accelerometer X/Y/Z values on screen.
7
Implement shake detection with the accelerometer — show a Toast when the user shakes the device.
8
Bonus: Display gyroscope rotation rates and alert when rotation exceeds a threshold.
Location, Camera & Sensors MCQ Practice
10 Basic MCQs10 Advanced MCQs
10 Basic Location, Camera & Sensors MCQs
1
Fused Location Provider from?
ASQLite
BGoogle Play services Location API
CRoom only
DGradle
Explanation: FusedLocationProviderClient combines GPS, WiFi, cell for best fix.
2
GPS permission is?
AINTERNET only
BCAMERA only
CACCESS_FINE_LOCATION
DVIBRATE
Explanation: COARSE for approximate; FINE for precise GPS.
3
CameraX is?
ABluetooth stack
BSQL ORM
CNotification API
DJetpack camera library abstracting device cameras
Explanation: CameraX simplifies preview, capture, and lifecycle binding.
4
SensorManager provides access to?
ADevice sensors (accelerometer, gyroscope)
BSQLite only
CPlay Store
DGradle daemon
Explanation: Register SensorEventListener for sensor updates.
5
Accelerometer measures?
AOnly temperature
BLinear acceleration including gravity
CBattery level
DNetwork speed
Explanation: Used for shake detection, orientation helpers.
6
Gyroscope measures?
ASound level
BGPS latitude
CRotational rate around axes
DLight color only
Explanation: Angular velocity for rotation-aware features.
7
takePicture in CameraX uses?
ABroadcastReceiver
BMediaPlayer
CRoom DAO
DImageCapture use case
Explanation: ImageCapture.takePicture saves photo to file or MediaStore.