18
18
package com.example.android.devbyteviewer
19
19
20
20
import android.app.Application
21
+ import android.os.Build
22
+ import androidx.work.*
23
+ import com.example.android.devbyteviewer.work.RefreshDataWorker
24
+ import kotlinx.coroutines.CoroutineScope
25
+ import kotlinx.coroutines.Dispatchers
26
+ import kotlinx.coroutines.launch
21
27
import timber.log.Timber
28
+ import java.util.concurrent.TimeUnit
22
29
23
30
/* *
24
31
* Override application to setup background work via WorkManager
25
32
*/
26
33
class DevByteApplication : Application () {
27
34
28
- // TODO (01) Create CoroutineScope variable applicationScope, using Dispatchers.Default.
35
+ val applicationScope = CoroutineScope ( Dispatchers .Default )
29
36
30
- // TODO (02) Create a delayedInit() function that calls setupRecurringWork() in
31
- // the coroutine you defined above.
32
-
33
- // TODO (04) Create a setupRecurringWork() function and use a Builder to define a
34
- // repeatingRequest variable to handle scheduling work.
37
+ private fun delayedInit () {
38
+ applicationScope.launch {
39
+ setupRecurringWork()
40
+ }
41
+ }
35
42
36
- // TODO (05) In setupRecurringWork(), get an instance of WorkManager and
37
- // launch call enqueuPeriodicWork() to schedule the work.
43
+ private fun setupRecurringWork () {
44
+ val constraints = Constraints .Builder ()
45
+ .setRequiredNetworkType(NetworkType .UNMETERED )
46
+ .setRequiresBatteryNotLow(true )
47
+ .setRequiresCharging(true )
48
+ .apply {
49
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .M ) {
50
+ setRequiresDeviceIdle(true )
51
+ }
52
+ }.build()
38
53
39
- // TODO (07) In setupRecurringWork(), define constraints to prevent work from occurring when
40
- // there is no network access or the device is low on battery.
54
+ val repeatingRequest
55
+ = PeriodicWorkRequestBuilder <RefreshDataWorker >(1 , TimeUnit .DAYS )
56
+ .setConstraints(constraints)
57
+ .build()
41
58
42
- // TODO (08) Add the constraints to the repeatingRequest definition.
59
+ WorkManager .getInstance().enqueueUniquePeriodicWork(
60
+ RefreshDataWorker .WORK_NAME ,
61
+ ExistingPeriodicWorkPolicy .KEEP ,
62
+ repeatingRequest)
63
+ }
43
64
44
65
/* *
45
66
* onCreate is called before the first screen is shown to the user.
@@ -50,6 +71,6 @@ class DevByteApplication : Application() {
50
71
override fun onCreate () {
51
72
super .onCreate()
52
73
Timber .plant(Timber .DebugTree ())
53
- // TODO (03) Call delayedInit().
74
+ delayedInit()
54
75
}
55
76
}
0 commit comments