Take a web map offline as a persistent background task using Android Jetpack’s WorkManager.

Use case
Taking a web map offline allows users continued productivity when their network connectivity is poor or nonexistent. For example, by taking a map offline, a field worker inspecting utility lines in remote areas could still access a feature’s location and attribute information.
How to use the sample
Once the map loads, zoom to the extent you want to take offline. The red border shows the extent that will be downloaded. Tap the “Take Map Offline” button to start the offline map job. The progress bar will show the job’s progress. When complete, the offline map will replace the online map in the map view. A notification is also shown with the current job’s progress along with a “Completed” or “Failure” notification when the job is done.
How it works
- Create an
ArcGISMapwith aPortalitem pointing to the web map. - Create
GenerateOfflineMapParametersspecifying the download area geometry, minimum scale, and maximum scale. - Create an
OfflineMapTaskwith the map. - Create the
OfflineMapJobwithOfflineMapTask.generateOfflineMap(params, downloadDirectoryPath). - Serialize the
OfflineMapJobto a file usingOfflineMapJob.toJson(). - Create a new
OneTimeWorkRequestwith an instance ofOfflineJobWorkerand set itsinputDatato theOfflineMapJob Jsonfilepath. - Use
WorkManager.enqueueUniqueWork()to schedule theOneTimeWorkRequest. - When the
OneTimeWorkRequestcompletes successfully, load the mobile map package from thedownloadDirectoryPathwithmapPackage.load(). - After it successfully loads, get the map and add it to the map view:
mapView.map = mapPackage.maps.first().
WorkManager and Background behavior
The OfflineJobWorker is a CoroutineWorker instance which is run as a long-running foreground service by the WorkManager. Check out Support for long-running workers for more info. Hence the behavior of the Worker depends on state of the application as follows:
When the app
- Moves into background
- The download continues in the background and push notifications are sent.
- Closed by swipe to kill
- The download continues in the background and push notifications are sent.
- Force stopped or crashes
- The worker is killed and the download/notifications stop.
- The worker is restarted upon next launch.
Notification behaviour
- Progress push notification are posted when the
OfflineJobWorkeris running. - Once the worker is done, either a “Completed” or “Failed” notification is posted.
- Tapping on the notification takes you back into the app, while tapping on the “Completed” notification will also load the offline map.
Relevant API
- GenerateOfflineMapJob
- GenerateOfflineMapParameters
- GenerateOfflineMapResult
- OfflineMapTask
- Portal
About the data
The map used in this sample shows the stormwater network within Naperville, IL, USA, with cartography designed for web and mobile devices with offline support.
Additional information
The creation of the offline map can be fine-tuned using parameter overrides for feature layers, or by using local basemaps to achieve more customised results.
Tags
background, download, notification, offline, save, service, web map, workmanager
Sample Code
/* * Copyright 2023 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager
import android.Manifest.permission.POST_NOTIFICATIONSimport android.content.pm.PackageManagerimport android.os.Buildimport android.os.Bundleimport android.util.Logimport android.view.ViewGroupimport com.esri.arcgismaps.sample.sampleslib.EdgeToEdgeCompatActivityimport androidx.core.app.ActivityCompatimport androidx.core.content.ContextCompatimport androidx.databinding.DataBindingUtilimport androidx.lifecycle.asFlowimport androidx.lifecycle.lifecycleScopeimport androidx.work.ExistingWorkPolicyimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.OutOfQuotaPolicyimport androidx.work.WorkInfoimport androidx.work.WorkManagerimport androidx.work.workDataOfimport com.arcgismaps.ApiKeyimport com.arcgismaps.ArcGISEnvironmentimport com.arcgismaps.Colorimport com.arcgismaps.geometry.Envelopeimport com.arcgismaps.geometry.Geometryimport com.arcgismaps.mapping.ArcGISMapimport com.arcgismaps.mapping.MobileMapPackageimport com.arcgismaps.mapping.PortalItemimport com.arcgismaps.mapping.symbology.SimpleLineSymbolimport com.arcgismaps.mapping.symbology.SimpleLineSymbolStyleimport com.arcgismaps.mapping.view.Graphicimport com.arcgismaps.mapping.view.GraphicsOverlayimport com.arcgismaps.mapping.view.ScreenCoordinateimport com.arcgismaps.portal.Portalimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapJobimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParametersimport com.arcgismaps.tasks.offlinemaptask.OfflineMapTaskimport com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager.databinding.GenerateOfflineMapUsingAndroidJetpackWorkmanagerActivityMainBindingimport com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager.databinding.OfflineJobProgressDialogLayoutBindingimport com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.google.android.material.snackbar.Snackbarimport kotlinx.coroutines.launchimport java.io.Fileimport kotlin.random.Random
// data parameter keys for the WorkManager// key for the NotificationId parameterconst val notificationIdParameter = "NotificationId"
// key for the json job file pathconst val jobParameter = "JsonJobPath"
class MainActivity : EdgeToEdgeCompatActivity() {
// set up data binding for the activity private val activityMainBinding: GenerateOfflineMapUsingAndroidJetpackWorkmanagerActivityMainBinding by lazy { DataBindingUtil.setContentView(this, R.layout.generate_offline_map_using_android_jetpack_workmanager_activity_main) }
private val mapView by lazy { activityMainBinding.mapView }
private val takeMapOfflineButton by lazy { activityMainBinding.takeMapOfflineButton }
private val resetMapButton by lazy { activityMainBinding.resetButton }
// instance of the WorkManager private val workManager by lazy { WorkManager.getInstance(this) }
// file path to store the offline map package private val offlineMapPath by lazy { getExternalFilesDir(null)?.path + getString(R.string.offlineMapFile) }
// shows the offline map job loading progress private val progressLayout by lazy { OfflineJobProgressDialogLayoutBinding.inflate(layoutInflater) }
// alert dialog view for the progress layout private val progressDialog by lazy { createProgressDialog().create() }
// used to uniquely identify the work request so that only one worker is active at a time // also allows us to query and observe work progress private val uniqueWorkName = "ArcgisMaps.Sample.OfflineMapJob.Worker"
// create a graphic overlay private val graphicsOverlay = GraphicsOverlay()
// represents bounds of the downloadable area of the map private val downloadArea = Graphic( symbol = SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.red, 2F) )
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
// request notifications permission requestNotificationPermission()
// authentication with an API key or named user is // required to access basemaps and other location services ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN) lifecycle.addObserver(mapView)
// set up the portal item to take offline setUpMapView()
// clear the preview map and display the Portal Item resetMapButton.setOnClickListener { // enable offline button takeMapOfflineButton.isEnabled = true resetMapButton.isEnabled = false // clear graphic overlays graphicsOverlay.graphics.clear() mapView.graphicsOverlays.clear()
// set up the portal item to take offline setUpMapView() } }
/** * Sets up a portal item and displays map area to take offline */ private fun setUpMapView() { // create a portal item with the itemId of the web map val portal = Portal(getString(R.string.portal_url)) val portalItem = PortalItem(portal, getString(R.string.item_id))
// add the graphic to the graphics overlay when it is created graphicsOverlay.graphics.add(downloadArea) // create and add a map with with portal item val map = ArcGISMap(portalItem) // apply mapview assignments mapView.apply { this.map = map graphicsOverlays.add(graphicsOverlay) }
lifecycleScope.launch { map.load().onFailure { // show an error and return if the map load failed showMessage("Error loading map: ${it.message}") return@launch }
// enable the take map offline button only after the map is loaded takeMapOfflineButton.isEnabled = true
// get the Control Valve layer from the map's operational layers val operationalLayer = map.operationalLayers.firstOrNull { layer -> layer.name == "Control Valve" } ?: return@launch showMessage("Error finding Control Valve layer")
// limit the map scale to the layer's scale map.maxScale = operationalLayer.maxScale ?: 0.0 map.minScale = operationalLayer.minScale ?: 0.0
mapView.viewpointChanged.collect { // upper left corner of the area to take offline val minScreenPoint = ScreenCoordinate(200.0, 200.0) // lower right corner of the downloaded area val maxScreenPoint = ScreenCoordinate( mapView.width - 200.0, mapView.height - 200.0 ) // convert screen points to map points val minPoint = mapView.screenToLocation(minScreenPoint) ?: return@collect val maxPoint = mapView.screenToLocation(maxScreenPoint) ?: return@collect // use the points to define and set an envelope for the downloadArea graphic val envelope = Envelope(minPoint, maxPoint) downloadArea.geometry = envelope } }
// set onclick listener for the takeMapOfflineButton takeMapOfflineButton.setOnClickListener { // if the downloadArea's geometry is not null downloadArea.geometry?.let { geometry -> // create an OfflineMapJob val offlineMapJob = createOfflineMapJob(map, geometry) // start the OfflineMapJob startOfflineMapJob(offlineMapJob) // show the progress dialog progressDialog.show() // disable the button takeMapOfflineButton.isEnabled = false } }
// start observing the worker's progress and status observeWorkStatus() }
/** * Creates and returns a new GenerateOfflineMapJob for the [map] and its [areaOfInterest] */ private fun createOfflineMapJob( map: ArcGISMap, areaOfInterest: Geometry ): GenerateOfflineMapJob { // check and delete if the offline map package file already exists File(offlineMapPath).deleteRecursively() // specify the min scale and max scale as parameters val maxScale = map.maxScale ?: 0.0 var minScale = map.minScale ?: 0.0 // minScale must always be larger than maxScale if (minScale <= maxScale) { minScale = maxScale + 1 } // set the offline map parameters val generateOfflineMapParameters = GenerateOfflineMapParameters( areaOfInterest, minScale, maxScale ).apply { // set job to cancel on any errors continueOnErrors = false } // create an offline map task with the map val offlineMapTask = OfflineMapTask(map) // create an offline map job with the download directory path and parameters and // return the job return offlineMapTask.createGenerateOfflineMapJob( generateOfflineMapParameters, offlineMapPath ) }
/** * Starts the [offlineMapJob] using OfflineJobWorker with WorkManager. The [offlineMapJob] is * serialized into a json file and the uri is passed to the OfflineJobWorker, since WorkManager * enforces a MAX_DATA_BYTES for the WorkRequest's data */ private fun startOfflineMapJob(offlineMapJob: GenerateOfflineMapJob) { // create a temporary file path to save the offlineMapJob json file val offlineJobJsonPath = getExternalFilesDir(null)?.path + getString(R.string.offlineJobJsonFile)
// create the json file val offlineJobJsonFile = File(offlineJobJsonPath) // serialize the offlineMapJob into the file offlineJobJsonFile.writeText(offlineMapJob.toJson())
// create a non-zero notification id for the OfflineJobWorker // this id will be used to post or update any progress/status notifications val notificationId = Random.Default.nextInt(1, 100)
// create a one-time work request with an instance of OfflineJobWorker val workRequest = OneTimeWorkRequestBuilder<OfflineJobWorker>() // run it as an expedited work .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) // add the input data .setInputData( // add the notificationId and the json file path as a key/value pair workDataOf( notificationIdParameter to notificationId, jobParameter to offlineJobJsonFile.absolutePath ) ).build()
// enqueue the work request to run as a unique work with the uniqueWorkName, so that // only one instance of OfflineJobWorker is running at any time // if any new work request with the uniqueWorkName is enqueued, it replaces any existing // ones that are active workManager.enqueueUniqueWork(uniqueWorkName, ExistingWorkPolicy.REPLACE, workRequest) }
/** * Starts observing any running or completed OfflineJobWorker work requests by capturing the * LiveData as a flow. The flow starts receiving updates when the activity is in started * or resumed state. This allows the application to capture immediate progress when * in foreground and latest progress when the app resumes or restarts. */ private fun observeWorkStatus() { // get the livedata observer of the unique work as a flow val liveDataFlow = workManager.getWorkInfosForUniqueWorkLiveData(uniqueWorkName).asFlow()
lifecycleScope.launch { // collect the live data flow to get the latest work info list liveDataFlow.collect { workInfoList -> if (workInfoList.isNotEmpty()) { // fetch the first work info as we only ever run one work request at any time val workInfo = workInfoList[0] // check the current state of the work request when (workInfo.state) { // if work completed successfully WorkInfo.State.SUCCEEDED -> { // load and display the offline map displayOfflineMap() // dismiss the progress dialog if (progressDialog.isShowing) { progressDialog.dismiss() } } // if the work failed or was cancelled WorkInfo.State.FAILED, WorkInfo.State.CANCELLED -> { // show an error message based on if it was cancelled or failed if (workInfo.state == WorkInfo.State.FAILED) { showMessage("Error generating offline map") } else { showMessage("Cancelled offline map generation") } // dismiss the progress dialog if (progressDialog.isShowing) { progressDialog.dismiss() } // enable the takeMapOfflineButton takeMapOfflineButton.isEnabled = true // this removes the completed WorkInfo from the WorkManager's database // otherwise, the observer will emit the WorkInfo on every launch // until WorkManager auto-prunes workManager.pruneWork() } // if the work is currently in progress WorkInfo.State.RUNNING -> { // get the current progress value val value = workInfo.progress.getInt("Progress", 0) // update the progress bar and progress text progressLayout.progressBar.progress = value progressLayout.progressTextView.text = "$value%" // shows the progress dialog if the app is relaunched and the // dialog is not visible if (!progressDialog.isShowing) { progressDialog.show() } } else -> { /* don't have to handle other states */ } } } } } }
/** * Loads the offline map package into the mapView */ private fun displayOfflineMap() { lifecycleScope.launch { // check if the offline map package file exists if (File(offlineMapPath).exists()) { // load it as a MobileMapPackage val mapPackage = MobileMapPackage(offlineMapPath) mapPackage.load().onFailure { // if the load fails, show an error and return showMessage("Error loading map package: ${it.message}") return@launch } // add the map from the mobile map package to the MapView mapView.map = mapPackage.maps.first() // clear all the drawn graphics graphicsOverlay.graphics.clear() // disable the button to take the map offline once the offline map is showing takeMapOfflineButton.isEnabled = false resetMapButton.isEnabled = true // this removes the completed WorkInfo from the WorkManager's database // otherwise, the observer will emit the WorkInfo on every launch // until WorkManager auto-prunes workManager.pruneWork() // display the offline map loaded message showMessage("Loaded offline map. Map saved at: $offlineMapPath") } else { showMessage("Offline map does not exists at path: $offlineMapPath") } } }
/** * Creates a progress dialog to show the OfflineMapJob worker progress. It cancels all the * running workers when the dialog is cancelled */ private fun createProgressDialog(): MaterialAlertDialogBuilder { // build and return a new alert dialog return MaterialAlertDialogBuilder(this).apply { // set it title setTitle(getString(R.string.dialog_title)) // allow it to be cancellable setCancelable(false) // set negative button configuration setNegativeButton("Cancel") { _, _ -> // cancel all the running work workManager.cancelAllWork() } // removes parent of the progressDialog layout, if previously assigned progressLayout.root.parent?.let { parent -> (parent as ViewGroup).removeAllViews() } // set the progressDialog Layout to this alert dialog setView(progressLayout.root) } }
/** * Request Post Notifications permission for API level 33+ * https://developer.android.com/develop/ui/views/notifications/notification-permission */ private fun requestNotificationPermission() { // request notification permission only for android versions >= 33 if (Build.VERSION.SDK_INT >= 33) { // check if push notifications permission is granted val permissionCheckPostNotifications = ContextCompat.checkSelfPermission(this@MainActivity, POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
// if permission is not already granted, request permission from the user if (!permissionCheckPostNotifications) { ActivityCompat.requestPermissions( this@MainActivity, arrayOf(POST_NOTIFICATIONS), 2 ) } } }
/** * Handle the permissions request response. */ override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_DENIED) { Snackbar.make( mapView, "Notification permissions required to show progress!", Snackbar.LENGTH_LONG ).show() } }
override fun onDestroy() { super.onDestroy() // dismiss the dialog when the activity is destroyed progressDialog.dismiss() }
private fun showMessage(message: String) { Log.e(localClassName, message) Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show() }}package com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager
import android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport androidx.work.WorkManager
/** * Custom BroadcastReceiver class that handles notification actions setup by WorkerNotification */class NotificationActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { // retrieve the data name or return if the context if null val extraName = context?.getString(R.string.notification_action) ?: return // get the actual data from the intent val action = intent?.getStringExtra(extraName) ?: "none" // if the action is cancel if (action == "Cancel") { // get the WorkManager instance and cancel all active workers WorkManager.getInstance(context).cancelAllWork() } }}/* * Copyright 2023 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager
import android.content.Contextimport android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNCimport android.os.Buildimport android.util.Logimport androidx.work.CoroutineWorkerimport androidx.work.WorkerParametersimport androidx.work.ForegroundInfoimport androidx.work.workDataOfimport com.arcgismaps.tasks.JobStatusimport com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapJobimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.launchimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.takeWhileimport java.io.File
/** * Class that runs a GenerateOfflineMapJob as a CoroutineWorker using WorkManager. */class OfflineJobWorker(private val context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
// notificationId passed by the activity private val notificationId by lazy { inputData.getInt(notificationIdParameter, 1) }
// WorkerNotification instance private val workerNotification by lazy { WorkerNotification(context, notificationId) }
// must override for api versions < 31 for backwards compatibility // with foreground services override suspend fun getForegroundInfo(): ForegroundInfo { return createForegroundInfo(0) }
/** * Creates and returns a new ForegroundInfo with a progress notification and the given * [progress] value. */ private fun createForegroundInfo(progress: Int): ForegroundInfo { // create a ForegroundInfo using the notificationId and a new progress notification return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ForegroundInfo( notificationId, workerNotification.createProgressNotification(progress), FOREGROUND_SERVICE_TYPE_DATA_SYNC ) } else { ForegroundInfo( notificationId, workerNotification.createProgressNotification(progress) ) } }
override suspend fun doWork(): Result { // get the job parameter which is the json file path val offlineJobJsonPath = inputData.getString(jobParameter) ?: return Result.failure() // load the json file val offlineJobJsonFile = File(offlineJobJsonPath) // if the file doesn't exist return failure if (!offlineJobJsonFile.exists()) { return Result.failure() } // create the GenerateOfflineMapJob from the json file val generateOfflineMapJob = GenerateOfflineMapJob.fromJsonOrNull(offlineJobJsonFile.readText()) // return failure if the created job is null ?: return Result.failure()
return try { // set this worker to run as a long-running foreground service // this will throw an exception, if the worker is launched when the app // is not in foreground setForeground(createForegroundInfo(0)) // check and delete if the offline map package file already exists // this check is needed, if the download has failed midway and is restarted later // by WorkManager File(generateOfflineMapJob.downloadDirectoryPath).deleteRecursively()
// start the generateOfflineMapJob // this job internally runs on a Dispatchers.IO context, hence this CoroutineWorker // can be run on the default Dispatchers.Default context generateOfflineMapJob.start()
// collect job progress, wait for the job to finish and get the result val jobResult = coroutineScope { // launch the progress collector in a new coroutine val progressCollectorJob = launch { // collect on progress until the job has completed in a success/failure generateOfflineMapJob.progress.takeWhile { generateOfflineMapJob.status.value != JobStatus.Failed && generateOfflineMapJob.status.value != JobStatus.Succeeded }.collect { progress -> // update the worker progress setProgress(workDataOf("Progress" to progress)) // update the ongoing progress notification setForeground(createForegroundInfo(progress)) } } // suspends until the generateOfflineMapJob has completed val result = generateOfflineMapJob.result() // cancel the progress collection coroutine if it is still running progressCollectorJob.cancel() // return the result result } // handle and return the result if (jobResult.isSuccess) { // if the job is successful show a final status notification workerNotification.showStatusNotification("Completed") Result.success() } else { // if the job has failed show a final status notification workerNotification.showStatusNotification("Failed") Result.failure() } } catch (cancellationException: CancellationException) { // a CancellationException is raised if the work is cancelled manually by the user // log and rethrow the cancellationException Log.e(javaClass.simpleName, "Offline map job canceled:", cancellationException) throw cancellationException } catch (exception: Exception) { // capture and log if any other exception occurs Log.e(javaClass.simpleName, "Offline map job failed:", exception) // post a job failed notification workerNotification.showStatusNotification("Failed") // return a failure result Result.failure() } finally { // cancel the job to free up any resources generateOfflineMapJob.cancel() } }}/* * Copyright 2023 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */
package com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager
import android.annotation.SuppressLintimport android.app.Notificationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompat
/** * Helper class that handles progress and status notifications on [applicationContext] for * the offline map job run using WorkManager. a non-zero [notificationId] is used to show * and update the progress and status notifications */class WorkerNotification( private val applicationContext: Context, private val notificationId: Int) {
// unique channel id for the NotificationChannel private val notificationChannelId by lazy { "${applicationContext.packageName}-notifications" }
// intent for notifications tap action that launch the MainActivity private val mainActivityIntent by lazy { // setup the intent to launch MainActivity val intent = Intent(applicationContext, MainActivity::class.java).apply { // launches the activity if not already on top and active flags = Intent.FLAG_ACTIVITY_SINGLE_TOP } // set the pending intent that will be passed to the NotificationManager PendingIntent.getActivity( applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE ) }
// intent for notification cancel action that launches a NotificationActionReceiver private val cancelActionIntent by lazy { // setup the intent to launch a NotificationActionReceiver val intent = Intent(applicationContext, NotificationActionReceiver::class.java).apply { // set this intent to only launch with this application package setPackage(applicationContext.packageName) // add the notification action as a string putExtra(applicationContext.getString(R.string.notification_action), "Cancel") } // set the pending intent that will be passed to the NotificationManager PendingIntent.getBroadcast( applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) }
init { // create the notification channel createNotificationChannel() }
/** * Creates and returns a new progress notification with the given [progress] value */ fun createProgressNotification(progress: Int): Notification { // use the default notification builder and set the progress to 0 return getDefaultNotificationBuilder( setOngoing = true, contentText = "Download in progress: $progress%" ).setProgress(100, progress, false) // add a cancellation action .addAction(0, "Cancel", cancelActionIntent) .build() }
/** * Creates and posts a new status notification with the [message] and dismisses any ongoing * progress notifications */ @SuppressLint("MissingPermission") fun showStatusNotification(message: String) { // build using the default notification builder with the status message val notification = getDefaultNotificationBuilder( setOngoing = false, contentText = message ).build().apply { // this flag dismisses the notification on opening flags = Notification.FLAG_AUTO_CANCEL }
with(NotificationManagerCompat.from(applicationContext)) { // cancel the visible progress notification using its id cancel(notificationId) // post the new status notification with a new notificationId notify(notificationId + 1, notification) } }
/** * Creates a new notification channel and adds it to the NotificationManager */ private fun createNotificationChannel() { // get the channel properties from resources val name = applicationContext.getString(R.string.notification_channel_name) val descriptionText = applicationContext.getString(R.string.notification_channel_description) val importance = NotificationManager.IMPORTANCE_HIGH // create a new notification channel with the properties val channel = NotificationChannel(notificationChannelId, name, importance).apply { description = descriptionText } // get the notification system service as a NotificationManager val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Add the channel to the NotificationManager notificationManager.createNotificationChannel(channel) }
/** * Creates and returns a new NotificationCompat.Builder with the given [contentText] * and as an ongoing notification based on [setOngoing] */ private fun getDefaultNotificationBuilder( setOngoing: Boolean, contentText: String ): NotificationCompat.Builder { return NotificationCompat.Builder(applicationContext, notificationChannelId) // sets the notifications title .setContentTitle(applicationContext.getString(R.string.notification_title)) // sets the content that is displayed on expanding the notification .setContentText(contentText) .setSmallIcon(com.esri.arcgismaps.sample.sampleslib.R.mipmap.arcgis_sdk_round) // sets it to only show the notification alert once, in case of progress .setOnlyAlertOnce(true) .setCategory(NotificationCompat.CATEGORY_PROGRESS) // ongoing notifications cannot be dismissed by swiping them away .setOngoing(setOngoing) // sets the onclick action to launch the mainActivityIntent .setContentIntent(mainActivityIntent) // sets it to show the notification immediately .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) }}