Phones have many features apps can use: the camera, GPS, sensors, Bluetooth and payments. Many of them need permissions and run into Android's limits on background work. This lesson shows the main tools and the rules that decide which one to use.
Choosing a background tool
- Coroutines: work while the app is open and tied to a screen.
- WorkManager: deferrable work that must finish even if the app closes or the phone restarts (sync, uploads). Add constraints: network type, charging, battery not low. Use
OneTimeWorkRequestorPeriodicWorkRequest(at least 15 minutes) and set a backoff for retries. - Foreground service: work the user knows about, with a notification: music, navigation, active workouts. Declare a foreground service type in the manifest.
- AlarmManager: time-exact alarms (alarm clocks, calendar reminders). Exact alarms need special permission on recent Android versions.
- JobScheduler: the system API under WorkManager; use WorkManager instead.
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork("sync", ExistingWorkPolicy.KEEP, request)
class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
override suspend fun doWork(): Result = try {
repo.sync(); Result.success()
} catch (e: IOException) { Result.retry() }
}
Android limits background work to protect battery: Doze mode, app standby buckets and background start restrictions. Do not fight them. Design for deferred, retriable work, and test on a real device.
Notifications
Create a channel (Android 8+), build the notification with NotificationCompat.Builder, and ask for POST_NOTIFICATIONS on Android 13+. Add a PendingIntent so tapping it opens the right screen.
Location and maps
- Use the Fused Location Provider from Google Play services. Ask for
ACCESS_COARSE_LOCATIONandACCESS_FINE_LOCATION; request background location only if truly needed, and explain why. getCurrentLocationfor one fix,requestLocationUpdatesfor tracking (stop it when the screen goes away to save battery).- Maps Compose shows a Google Map with
GoogleMap { Marker(...) }. It needs a Maps API key from Google Cloud, kept out of the repository and restricted to your app. - Geofencing notifies you when the user enters or leaves an area, using
GeofencingClient. - Decide with the user in mind: precise location is sensitive. Ask only when needed, and delete what you do not need.
Camera, media and files
- CameraX for photo, video and analysis. PickVisualMedia for the photo picker, which needs no permission.
- Media3 (ExoPlayer) for audio and video playback; MediaRecorder for recording audio and video.
- Files: use app-specific storage for your own files, the Storage Access Framework for documents the user chooses, and MediaStore for shared media. Broad storage access is restricted.
- PDF:
PdfDocumentcreates PDFs from views or canvas;PdfRenderershows pages.
Sensors and connectivity
- SensorManager with
Sensor.TYPE_ACCELEROMETERand aSensorEventListener(register inonResume, unregister inonPause, or with DisposableEffect). Use step counter sensors or Health Connect for fitness data, with the user's permission. - Bluetooth Low Energy needs
BLUETOOTH_SCANandBLUETOOTH_CONNECTpermissions on recent Android versions; scan, connect with GATT and read characteristics. - NFC reads tags through
NfcAdapterand intents. - Wi-Fi APIs are limited in recent versions; use
ConnectivityManagerfor state. - Speech:
SpeechRecognizerfor speech to text andTextToSpeechfor the reverse. Contacts and Calendar use content providers and need their own permissions.
Payments
Never process cards yourself. For digital goods sold in the app, Google Play requires Play Billing. For physical goods and services, use a payment provider's SDK (Google Pay with a gateway such as Stripe or Razorpay). The app collects a payment token from the SDK, and your server talks to the gateway and confirms the order. The food-delivery and e-commerce projects use a demo flow only.
Your task
- Schedule a WorkManager job with a network constraint and watch it in the Background Task Inspector.
- Show your location on a Maps Compose screen with your own key.
- Read the accelerometer and show a live number.
- List which permission each feature above needs and when you would ask.
How to check it worked
- Background work survives closing the app.
- Location updates stop when the screen closes.
- Payment secrets stay on the server.