Device Capabilities, Background Work and NotificationsIntroductionAndroid applications are valuable partly because they can use capabilities built into a mobile device: cameras, microphones, media storage, geographic location, motion sensors, network connectivity and system notifications. These capabilities also create responsibilities. They may reveal personal information, consume battery, expose sensitive images or recordings, and interrupt users at inappropriate times. Modern Android therefore applies two complementary principles. First, access to sensitive capabilities is controlled through permissions and user choice. Second, work that continues beyond the visible screen is controlled through lifecycle-aware APIs, execution limits and notification requirements. A professional Android developer must design for both functionality and restraint. This chapter explains how to request and use permissions responsibly, access camera and media features, obtain location and sensor data, schedule background work, run foreground services when justified, and deliver useful notifications. Examples use Kotlin and contemporary Android concepts such as AndroidX, WorkManager, runtime permissions, notification channels and lifecycle-aware components. Learning ObjectivesBy the end of this chapter, you should be able to: - Explain Android’s permission model and apply least-privilege design.
- Request dangerous permissions at an appropriate moment and handle denial safely.
- Describe responsible use of camera, media, location and sensors.
- Select suitable APIs for immediate, scheduled, persistent and user-visible work.
- Explain the roles of WorkManager, coroutines, alarms and foreground services.
- Create notification channels and design meaningful notifications.
- Evaluate privacy, battery, accessibility and reliability implications in an application.
1. Android’s Capability and Trust ModelA capability is a device or operating-system feature that an application can use, such as taking a photograph or reading the device’s location. Android does not treat all capabilities equally. Some operations are available without permission; others require an installation-time or runtime grant. 1.1 Normal and dangerous permissionsNormal permissions protect features with relatively low privacy or security risk. The system grants them automatically when appropriate. Dangerous permissions protect information or operations such as location, camera, microphone, contacts and calendar data. On current Android versions, an application declares these permissions in AndroidManifest.xml and requests user approval while running. A manifest declaration is necessary but not sufficient: <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> The application should request a permission only when the user reaches the feature that needs it. Asking for every permission at startup weakens trust and increases unnecessary denial. The request should be preceded by a concise explanation of the feature’s purpose, not by a misleading statement such as “permission required for the app to work” when only one optional feature is affected. A typical Kotlin pattern is: private val cameraPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) openCamera()
else showCameraUnavailableMessage()
}
fun onTakePhotoSelected() {
if (ContextCompat.checkSelfPermission(
requireContext(), Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED) {
openCamera()
} else {
cameraPermission.launch(Manifest.permission.CAMERA)
}
}The callback must handle both outcomes. If access is denied, the user should still be able to use unrelated features. If the user has permanently declined access or selected a setting equivalent to “do not ask again,” the application can explain how to change the setting, but it must not repeatedly prompt or obstruct the user. 1.2 Least privilege and data minimisationLeast privilege means requesting only the capability needed for a clearly defined task. Data minimisation means collecting, retaining and transmitting no more personal data than necessary. For example, an application that needs to attach a single photograph may use the system camera contract and save one selected image rather than requesting broad access to the entire media library. Permission decisions should also consider scope and duration. A one-time location request is preferable to continuous background location when the user is merely finding a nearby store. A coarse location may be sufficient for regional weather, whereas turn-by-turn navigation may require fine location. 1.3 Permission lifecyclePermissions can change after installation. A user can revoke access in Settings, an operating-system update can alter policy, and an application can be paused or resumed. Therefore, permission checks belong immediately before the operation, not only in onCreate(). Applications should also expect unavailable hardware, restricted profiles, interrupted activities and process recreation. 2. Camera and Media2.1 Choosing an access strategyThere are two broad approaches to camera use: - System camera intents or contracts: the application delegates capture to an installed camera application. This is comparatively simple and limits the application’s direct handling of camera hardware.
- CameraX or Camera2: the application controls a camera preview and capture pipeline. CameraX is generally preferred for ordinary application development because it provides lifecycle-aware use cases and supports common devices more consistently. Camera2 offers lower-level control for specialised applications.
When the requirement is simply “take a photograph,” using an Activity Result contract such as TakePicture() is often more appropriate than building a custom camera screen. A content URI should be created with a FileProvider or MediaStore, rather than exposing a raw file path. 2.2 Secure media handlingImages and videos may contain faces, documents, location metadata and other sensitive information. Good practice includes: - explaining why capture is needed;
- using scoped storage and MediaStore where appropriate;
- avoiding broad media permissions when a system picker is sufficient;
- validating file type and size;
- removing unnecessary metadata before sharing;
- protecting temporary files and deleting them when no longer needed;
- obtaining consent before uploading or sharing media.
The system photo picker is especially useful when a user chooses existing media. It allows selection without granting the application unrestricted access to the media collection. Applications should not assume that a selected item has a conventional local filesystem path; they should read it through its content URI and use the resolver APIs. 2.3 Camera and microphone indicatorsRecent Android releases provide visible indicators and privacy controls for camera and microphone use. An application must not attempt to conceal active capture. Capture should be tied to a visible user action or clearly communicated foreground operation. Recording in the background without informed consent is both unethical and potentially unlawful. 3. LocationLocation can be obtained from GPS, Wi-Fi, cellular networks and other providers. Android’s fused location services combine sources to provide an efficient result. Location accuracy is not a fixed promise: it varies with hardware, signal conditions, permissions, battery settings and environment. 3.1 Coarse, fine and background locationCoarse location provides an approximate position. Fine location provides greater precision when the user and system permit it. Background location is a separate, more sensitive use case and is subject to additional policy and user controls. An application should first demonstrate a clear foreground use case before requesting background access. A useful design question is not “Can the application obtain precise location?” but “What is the least precise location that still achieves the user’s goal?” A city guide may need only an approximate area. A navigation service may need frequent, precise updates while navigation is active. 3.2 Location lifecycle and energyLocation updates should be started when needed and removed when the feature ends. A screen showing a nearby venue may need one current fix, while navigation needs a stream of updates. Continuous high-accuracy updates are expensive and may drain the battery. The developer should select an interval and priority appropriate to the task, but these are requests rather than guarantees. The system may deliver updates less frequently or batch them. The application should tolerate missing, delayed or stale data and display uncertainty rather than presenting a false impression of precision. Location data should be protected in transit and at rest. Retention periods should be limited, and users should be able to understand and control whether history is stored. 4. Sensors and Device StateAndroid devices may include accelerometers, gyroscopes, magnetometers, light sensors, proximity sensors and other hardware. Sensor availability varies by device, so applications must query the SensorManager rather than assume that a sensor exists. Sensor readings are measurements, not unquestionable facts. They may contain noise, bias, drift and interference. For a basic motion feature, an application can register a listener while the relevant Activity or service is active and unregister it when no longer needed. High-frequency sampling consumes energy; the sampling rate should match the feature’s actual needs. For example, a pedometer-like feature may require filtering and calibration, whereas a simple screen-orientation reaction can use lower-frequency measurements. A developer should avoid collecting raw sensor streams indefinitely when a derived value is sufficient. Sensor data can also reveal behaviour patterns, so privacy considerations apply even when the sensor itself is not traditionally labelled “personal data.” 5. Background Work and Android Execution LimitsBackground work is any work performed when the application is not currently visible or when a user is not directly interacting with it. Examples include uploading a photograph, synchronising records, processing a downloaded file and refreshing application data. Older Android applications could keep background services running for long periods. Modern Android restricts this behaviour to protect battery life, memory and user privacy. A robust design begins by classifying the work: | Requirement | Suitable mechanism |
|---|
| Brief work while a screen is visible | Kotlin coroutine tied to a lifecycle | | Deferrable, reliable work | WorkManager | | Exact user-visible time | AlarmManager, subject to current restrictions | | Ongoing, user-visible operation | Foreground service with notification | | Immediate UI update from existing data | ViewModel and observable state |
5.1 Coroutines and lifecycle scopeA coroutine is appropriate for a short operation associated with a screen, such as loading a record from a repository. It should be launched in viewModelScope or lifecycleScope, not in an unstructured global scope. Structured concurrency ensures that child work is cancelled when its owner is destroyed or no longer relevant. viewModelScope.launch {
uiState.value = UiState.Loading
uiState.value = try {
UiState.Success(repository.loadProfile())
} catch (e: IOException) {
UiState.Error("Unable to load profile")
}
}Cancellation is normal and should not be treated as an application failure. Network and disk operations should be moved off the main thread, and the interface should remain responsive. 5.2 WorkManagerWorkManager is designed for work that must eventually run and can usually be deferred. It persists work across process termination and, subject to constraints, device restart. It supports constraints such as network availability, charging and sufficient battery. It is not a guarantee of immediate execution and is not intended for millisecond-precise timing. val upload = OneTimeWorkRequestBuilder<UploadWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
WorkManager.getInstance(context).enqueue(upload)A Worker should report success, failure or retry. Retry should be used for transient problems such as temporary network unavailability, ideally with backoff. Permanent validation errors should not be retried indefinitely. Work should be idempotent: if it runs more than once, it should not create duplicate orders or duplicate charges. Idempotency can be supported with unique operation identifiers and server-side duplicate detection. 5.3 AlarmsAlarmManager is appropriate when an event must be associated with a clock time, such as an alarm-clock function or a calendar reminder. Exact alarms are restricted on some Android versions because they can significantly affect battery life. An application should use inexact alarms when exact timing is not essential and comply with applicable permission and policy requirements. 5.4 Foreground servicesA foreground service is for work that the user can reasonably perceive as ongoing, such as active navigation, a phone call, or media playback. It must display a persistent notification and must follow service-type and start restrictions applicable to the target Android version. It is not a general escape route for arbitrary background processing. The notification should identify the operation and provide a meaningful way to stop or control it. The service should end as soon as the operation finishes. Starting a foreground service merely to keep an application alive is poor engineering and may be blocked by the platform. 6. NotificationsA notification is a communication from an application to the user outside the application’s immediate interface. It should be timely, relevant and actionable. Notifications are not a substitute for fixing a poor in-app workflow. 6.1 Channels and permissionOn Android 8.0 and later, notifications belong to channels. A channel has a user-controlled importance and behaviour. Channels should represent meaningful categories, such as “Order updates” or “Messages,” rather than being created for every individual message. Once created, some channel settings are controlled by the user and cannot be silently overridden by the application. On Android versions that require it, the application must request notification permission at runtime. Permission should be requested in context—for example, after the user enables delivery tracking—rather than immediately on first launch. val channel = NotificationChannel(
"orders",
"Order updates",
NotificationManager.IMPORTANCE_DEFAULT
)
getSystemService(NotificationManager::class.java)
.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(this, "orders")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Order dispatched")
.setContentText("Your order is on its way")
.setAutoCancel(true)
.build()A valid small icon is required. Notification text should be concise, and sensitive information should not be exposed on a lock screen unless the user’s privacy settings permit it. The notification should open the relevant destination through a PendingIntent, and actions should be understandable and safe. 6.2 Notification design principlesEffective notifications: - communicate a clear reason for interruption;
- use appropriate channel importance;
- avoid repeated, promotional or duplicate alerts;
- group related messages;
- support dismissal and meaningful actions;
- respect quiet hours, accessibility and user preferences;
- do not reveal private content unnecessarily;
- remain useful if delivery is delayed.
A foreground-service notification is persistent by design, but it should still describe the active operation accurately. An application must not disguise an ordinary background task as a foreground service simply to avoid restrictions. 7. A Decision Framework for Capability-Using FeaturesA practical design sequence is: - Define the user goal. State the feature in user terms.
- Identify the minimum data and capability. Prefer selection over broad access and approximate data over precise data when adequate.
- Choose the platform API. Use system contracts, pickers, lifecycle APIs and WorkManager where appropriate.
- Explain and request access in context. The user should understand the benefit before granting access.
- Design denial and failure paths. The feature should degrade gracefully.
- Control lifetime. Stop sensors, location updates, camera sessions and services when finished.
- Protect data. Limit retention, secure transmission and avoid unnecessary logging.
- Test adverse conditions. Test permission denial, revoked permission, no sensor, offline operation, process death, reboot and battery restrictions.
This sequence integrates technical reliability with ethical design. A feature is not complete merely because it works on a developer’s device with every permission granted. 8. Illustrative Case: CampusSafe EscortBackgroundCampusSafe is an illustrative student application that allows a student to request a walking escort from a campus security team. The feature uses location, network communication and notifications. It does not need camera, microphone or continuous location outside an active escort. ProblemAn early prototype requested fine location, background location, camera and notification access at startup. It ran a continuous background service and produced frequent notifications. Students denied permissions, battery use increased, and the security team received incomplete location data. AnalysisThe actual user goal was limited: while an escort request was active, the security team needed the student’s current position and status updates. Background location was potentially justified only during an active escort, not during ordinary application use. Camera access was unrelated and should be removed. A continuous service was appropriate only while the escort was visibly active and required a persistent notification. Approach and solutionThe redesigned application follows these steps: - It requests notification permission when the student enables escort updates.
- It requests foreground location when the student views nearby security resources.
- When an escort is confirmed, it explains why location must continue during the active request and follows applicable background-location policy.
- It starts a properly declared foreground service only for the active escort, with a notification containing a “End escort” action.
- It sends location updates at a rate suitable for safety needs and stops updates immediately when the escort ends.
- It stores only the minimum trip information required by institutional policy and restricts access to authorised staff.
- It uses WorkManager for deferred upload of non-urgent trip records when network connectivity returns.
- If permission is denied, it offers a phone contact or campus map instead of blocking all application functions.
OutcomeThe redesign reduces unnecessary permissions, gives users a clear explanation, limits battery-intensive work to the period of genuine need and provides an accessible alternative when location is unavailable. Security staff receive more meaningful data because the system distinguishes active escort tracking from ordinary application use. Learning pointsThe case demonstrates that responsible capability use is primarily a design problem. Technical APIs matter, but permission timing, data minimisation, clear user communication and lifecycle control determine whether the result is trustworthy. 9. Testing, Reliability and GovernanceTesting should include at least the following conditions: - permission granted, denied and later revoked;
- approximate rather than precise location;
- device without the requested sensor or camera;
- rotation, process death and Activity recreation;
- no network, metered network and restricted background data;
- battery saver and Doze conditions;
- reboot and application update;
- notification permission denied or channel disabled;
- work executed more than once;
- lock-screen privacy and accessibility settings.
Developers should inspect logs for accidental personal data, use secure transport, protect tokens and avoid placing sensitive information in notification text. Organisations may also be subject to privacy and communications laws, institutional policies and platform distribution rules. Legal compliance depends on jurisdiction, but ethical principles remain broadly applicable: informed choice, purpose limitation, proportionality, security and accountability. Artificial intelligence can be relevant when analysing sensor streams, classifying images or predicting user needs, but it does not remove permission or privacy obligations. If an AI feature processes photographs, location traces or voice data, the application must explain the processing purpose, minimise collection and provide appropriate controls. Model output should not be treated as automatically accurate, especially in safety-sensitive contexts. Best Practices Checklist- Request sensitive permissions only at the point of need.
- Prefer system pickers and contracts to broad storage access.
- Use coarse or foreground-only location when it satisfies the feature.
- Stop camera, sensor and location resources promptly.
- Use lifecycle-aware coroutines for screen-scoped work.
- Use WorkManager for persistent, deferrable work.
- Use foreground services only for ongoing, user-visible operations.
- Make background work retryable and idempotent.
- Create meaningful notification channels and respect user settings.
- Provide useful behaviour when access is denied or hardware is absent.
- Test process death, reboot, offline conditions and revoked permissions.
- Minimise, secure and govern all collected data.
Chapter SummaryAndroid device capabilities provide powerful opportunities but expose users to privacy, security, battery and interruption risks. The permission model requires manifest declarations, runtime requests where applicable, contextual explanations and graceful handling of denial. Least privilege and data minimisation should guide decisions about camera, media, location and sensors. Camera and media features should prefer system contracts and pickers when full hardware or library control is unnecessary. Location should be selected by purpose, precision and duration, while sensor use should account for hardware variation, noise and energy consumption. Background work must respect Android execution limits: lifecycle-aware coroutines suit short screen-related tasks, WorkManager suits reliable deferrable work, alarms suit time-based events, and foreground services suit ongoing user-visible operations. Notifications require meaningful channels, appropriate permission, concise content, privacy awareness and actionable destinations. The CampusSafe case illustrates that responsible implementation combines API selection, lifecycle management, user communication, security and governance. Professional Android development therefore means not only making a feature function, but making its use proportionate, understandable, resilient and respectful. Key TermsPermission: Authorisation allowing an application to use a protected system capability. Runtime permission: A permission requested from the user while the application is running. Least privilege: Granting and using only the access required for a defined task. Data minimisation: Collecting, processing and retaining no more data than necessary. Scoped storage: Android’s model limiting unrestricted access to shared filesystem content. Content URI: A URI that identifies data provided through Android’s content-provider system. Coarse location: Approximate geographic location. Fine location: More precise geographic location, subject to user and system controls. Sensor: Hardware or software component that reports measurements about the device or environment. Lifecycle: The sequence of states through which an Android component passes. Coroutine: A Kotlin construct for cooperative, structured asynchronous work. WorkManager: AndroidX API for reliable, deferrable background work. Alarm: A system event scheduled for a clock time or elapsed-time condition. Foreground service: A service for ongoing work that is apparent to the user and requires a notification. Notification: A system message communicating application information outside the immediate interface. Notification channel: A user-configurable category controlling notification behaviour. Idempotency: A property in which repeating an operation produces the same intended result without harmful duplication. Doze: An Android power-management state that restricts some background activity. Data minimisation: Limiting personal-data handling to what the purpose requires. System contract: A standard Android interaction, such as taking a picture or selecting media, delegated through an Activity Result API. Review QuestionsShort Answer Questions- Why should an application request a sensitive permission at the point of need rather than at startup?
- Distinguish coarse location from fine location.
- What type of work is WorkManager designed to support?
- Why are notification channels required on recent Android versions?
- State two reasons for unregistering a sensor listener or location callback.
Long Answer Questions- Explain Android’s permission model and discuss how least privilege and data minimisation should influence application design.
- Compare system camera contracts, CameraX and Camera2, including situations in which each approach may be appropriate.
- Compare lifecycle-aware coroutines, WorkManager, AlarmManager and foreground services.
- Describe the design principles of trustworthy notifications, including channels, privacy and user control.
- Explain how an application should design for permission denial, process death, offline operation and device variation.
Analytical / Application Questions- A weather application requests precise background location, camera access and microphone access when it first opens. Analyse the design and propose a less intrusive permission and API strategy.
- A delivery application must upload proof-of-delivery photographs, even if the process is killed or the network temporarily disappears. Design an approach using media URIs, WorkManager, retry behaviour and idempotency.
- A navigation application tracks an active journey while the screen is locked and displays progress to the user. Decide whether a foreground service is justified and specify the permission, notification, lifecycle and battery considerations that should be addressed.
Multiple Choice Questions with AnswersQuestion 1Which principle means requesting only the access required for a particular feature? A. Least privilege B. Eventual consistency C. Progressive rendering D. Cache invalidation Correct Answer: A. Least privilege Question 2Which Android mechanism is generally most suitable for reliable, deferrable background work? A. A global coroutine B. WorkManager C. A continuously running Activity D. A sensor listener Correct Answer: B. WorkManager Question 3What should an application do when a user denies camera permission for an optional photo feature? A. Crash immediately B. Repeatedly display the permission dialog C. Allow unrelated features and explain the limitation D. Silently enable the camera Correct Answer: C. Allow unrelated features and explain the limitation Question 4What is a principal purpose of a foreground-service notification? A. To hide background activity B. To make ongoing user-visible work apparent C. To replace all runtime permissions D. To guarantee exact execution time Correct Answer: B. To make ongoing user-visible work apparent Question 5Which choice usually minimises access when a user selects an existing photograph? A. Requesting unrestricted filesystem access B. Using a system photo picker C. Starting a foreground service D. Registering a gyroscope listener Correct Answer: B. Using a system photo picker Question 6Why should background work be designed to be idempotent? A. It guarantees faster execution B. It prevents every network failure C. Repeated execution does not create harmful duplicates D. It removes the need for authentication Correct Answer: C. Repeated execution does not create harmful duplicates Question 7Which API is most appropriate for a clock-based calendar reminder when exact timing is genuinely required, subject to platform restrictions? A. AlarmManager B. CameraX C. SensorManager D. MediaStore Correct Answer: A. AlarmManager Question 8What should an application do with a location callback when an active location feature ends? A. Keep it registered permanently B. Remove it promptly C. Convert it into a notification channel D. Store it as a camera URI Correct Answer: B. Remove it promptly Question 9On Android 8.0 and later, notifications are organised into what structure? A. Sensor groups B. Permission bundles C. Notification channels D. Content providers Correct Answer: C. Notification channels Question 10Which statement about sensor readings is most accurate? A. They are always exact and identical across devices B. They may contain noise and hardware-dependent variation C. They never consume battery D. They automatically provide geographic coordinates Correct Answer: B. They may contain noise and hardware-dependent variation
|