Background Work and Device Features: Location, Maps, Sensors, Payments

Android Development with Kotlin: 21 Real Projects · Production Android · 4 min read · Updated

Pick the right tool

  1. Work tied to a visible screen uses coroutines.
  2. Work that must finish later, even if the app closes, uses WorkManager.
  3. Work the user is aware of, like music, runs in a foreground service with a notification.
  4. Only truly time-exact tasks such as alarms use AlarmManager.

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 OneTimeWorkRequest or PeriodicWorkRequest (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_LOCATION and ACCESS_FINE_LOCATION; request background location only if truly needed, and explain why.
  • getCurrentLocation for one fix, requestLocationUpdates for 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: PdfDocument creates PDFs from views or canvas; PdfRenderer shows pages.

Sensors and connectivity

  • SensorManager with Sensor.TYPE_ACCELEROMETER and a SensorEventListener (register in onResume, unregister in onPause, or with DisposableEffect). Use step counter sensors or Health Connect for fitness data, with the user's permission.
  • Bluetooth Low Energy needs BLUETOOTH_SCAN and BLUETOOTH_CONNECT permissions on recent Android versions; scan, connect with GATT and read characteristics.
  • NFC reads tags through NfcAdapter and intents.
  • Wi-Fi APIs are limited in recent versions; use ConnectivityManager for state.
  • Speech: SpeechRecognizer for speech to text and TextToSpeech for 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

  1. Schedule a WorkManager job with a network constraint and watch it in the Background Task Inspector.
  2. Show your location on a Maps Compose screen with your own key.
  3. Read the accelerometer and show a live number.
  4. 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.

Frequently asked questions

Why did my background work not run on time?

Doze and battery limits delay work. WorkManager is designed to run it when the system allows. Use a foreground service or an exact alarm only when the feature really needs it.

Do I need a Maps API key?

Yes, Google Maps needs a key from Google Cloud. Restrict it to your app and keep it out of public code.

Can the app store card numbers?

No. Use a payment provider SDK so card data goes to the provider, and let your server confirm payments.