1 /*
2  * Copyright 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.work.impl.background.systemjob
18 
19 import android.app.job.JobInfo
20 import android.app.job.JobScheduler
21 import android.content.Context
22 import android.os.Build
23 import androidx.annotation.RequiresApi
24 import androidx.work.Configuration
25 import androidx.work.Logger
26 import androidx.work.impl.WorkDatabase
27 import androidx.work.impl.background.systemjob.SystemJobScheduler.getPendingJobs
28 import androidx.work.loge
29 
30 internal const val WORKMANAGER_NAMESPACE = "androidx.work.systemjobscheduler"
31 
32 // using SystemJobScheduler as tag for simplicity, because everything here is about
33 // SystemJobScheduler
34 private val TAG = Logger.tagWithPrefix("SystemJobScheduler")
35 
36 @get:RequiresApi(21)
37 internal val Context.wmJobScheduler: JobScheduler
38     get() {
39         val defaultJobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
40         return if (Build.VERSION.SDK_INT >= 34) {
41             JobScheduler34.forNamespace(defaultJobScheduler)
42         } else defaultJobScheduler
43     }
44 
45 @RequiresApi(34)
46 private object JobScheduler34 {
forNamespacenull47     fun forNamespace(jobScheduler: JobScheduler): JobScheduler {
48         return jobScheduler.forNamespace(WORKMANAGER_NAMESPACE)
49     }
50 }
51 
52 @RequiresApi(21)
53 private object JobScheduler21 {
getAllPendingJobsnull54     fun getAllPendingJobs(jobScheduler: JobScheduler): List<JobInfo> {
55         return jobScheduler.allPendingJobs
56     }
57 }
58 
59 @get:RequiresApi(21)
60 val JobScheduler.safePendingJobs: List<JobInfo>?
61     get() {
62         return try {
63             // Note: despite what the word "pending" and the associated Javadoc might imply, this is
64             // actually a list of all unfinished jobs that JobScheduler knows about for the current
65             // process.
66             JobScheduler21.getAllPendingJobs(this)
67         } catch (exception: Throwable) {
68             // OEM implementation bugs in JobScheduler cause the app to crash. Avoid crashing.
69             // see b/134028937
<lambda>null70             loge(TAG, exception) { "getAllPendingJobs() is not reliable on this device." }
71             null
72         }
73     }
74 
75 @RequiresApi(23)
createErrorMessagenull76 internal fun createErrorMessage(
77     context: Context,
78     workDatabase: WorkDatabase,
79     configuration: Configuration,
80 ): String {
81     val totalLimit = if (Build.VERSION.SDK_INT >= 31) 150 else 100
82     val dbScheduledCount = workDatabase.workSpecDao().getScheduledWork().size
83     val jobSchedulerStats =
84         if (Build.VERSION.SDK_INT >= 34) {
85             val namespacedScheduler = context.wmJobScheduler
86             val allJobsInNamespace = namespacedScheduler.safePendingJobs
87             if (allJobsInNamespace != null) {
88                 val pendingJobs = getPendingJobs(context, namespacedScheduler)
89                 val diff =
90                     if (pendingJobs != null) allJobsInNamespace.size - pendingJobs.size else 0
91 
92                 val nonWmJobsMessage =
93                     when (diff) {
94                         0 -> null
95                         else -> "$diff of which are not owned by WorkManager"
96                     }
97 
98                 val defaultJobScheduler =
99                     context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
100                 val wmJobsInDefault = getPendingJobs(context, defaultJobScheduler)?.size ?: 0
101 
102                 val defaultNamespaceMessage =
103                     when (wmJobsInDefault) {
104                         0 -> null
105                         else -> "$wmJobsInDefault from WorkManager in the default namespace"
106                     }
107 
108                 listOfNotNull(
109                         "${allJobsInNamespace.size} jobs in \"$WORKMANAGER_NAMESPACE\" namespace",
110                         nonWmJobsMessage,
111                         defaultNamespaceMessage
112                     )
113                     .joinToString(",\n")
114             } else "<faulty JobScheduler failed to getPendingJobs>"
115         } else {
116             when (val pendingJobs = getPendingJobs(context, context.wmJobScheduler)) {
117                 null -> "<faulty JobScheduler failed to getPendingJobs>"
118                 else -> "${pendingJobs.size} jobs from WorkManager"
119             }
120         }
121 
122     return "JobScheduler $totalLimit job limit exceeded.\n" +
123         "In JobScheduler there are $jobSchedulerStats.\n" +
124         "There are $dbScheduledCount jobs tracked by WorkManager's database;\n" +
125         "the Configuration limit is ${configuration.maxSchedulerLimit}."
126 }
127