Generate offline map using Android Jetpack WorkManager

View on GitHubSample viewer app

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

Image of generate offline map using Android Jetpack 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

  1. Create an ArcGISMap with a Portal item pointing to the web map.
  2. Create GenerateOfflineMapParameters specifying the download area geometry, minimum scale, and maximum scale.
  3. Create an OfflineMapTask with the map.
  4. Create the OfflineMapJob with OfflineMapTask.generateOfflineMap(params, downloadDirectoryPath).
  5. Serialize the OfflineMapJob to a file using OfflineMapJob.toJson().
  6. Create a new OneTimeWorkRequest with an instance of OfflineJobWorker and set its inputData to the OfflineMapJob Json filepath.
  7. Use WorkManager.enqueueUniqueWork() to schedule the OneTimeWorkRequest.
  8. When the OneTimeWorkRequest completes successfully, load the mobile map package from the downloadDirectoryPath with mapPackage.load().
  9. 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

  1. Moves into background
    1. The download continues in the background and push notifications are sent.
  2. Closed by swipe to kill
    1. The download continues in the background and push notifications are sent.
  3. Force stopped or crashes
    1. The worker is killed and the download/notifications stop.
    2. The worker is restarted upon next launch.

Notification behaviour

  1. Progress push notification are posted when the OfflineJobWorker is running.
  2. Once the worker is done, either a "Completed" or "Failed" notification is posted.
  3. 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

MainActivity.ktMainActivity.ktOfflineJobWorker.ktWorkerNotification.ktNotificationActionReceiver.kt
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
 * 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_NOTIFICATIONS
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.asFlow
import androidx.lifecycle.lifecycleScope
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.Color
import com.arcgismaps.geometry.Envelope
import com.arcgismaps.geometry.Geometry
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.MobileMapPackage
import com.arcgismaps.mapping.PortalItem
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.ScreenCoordinate
import com.arcgismaps.portal.Portal
import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapJob
import com.arcgismaps.tasks.offlinemaptask.GenerateOfflineMapParameters
import com.arcgismaps.tasks.offlinemaptask.OfflineMapTask
import com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager.databinding.ActivityMainBinding
import com.esri.arcgismaps.sample.generateofflinemapusingandroidjetpackworkmanager.databinding.OfflineJobProgressDialogLayoutBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import java.io.File
import kotlin.random.Random

// data parameter keys for the WorkManager
// key for the NotificationId parameter
const val notificationIdParameter = "NotificationId"

// key for the json job file path
const val jobParameter = "JsonJobPath"

class MainActivity : AppCompatActivity() {

    // set up data binding for the activity
    private val activityMainBinding: ActivityMainBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.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.API_KEY)
        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()
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.