On Android 15, why does a dash-cam app's dataSync foreground service uploading a day of clips crash with 'did not stop within its timeout', and how do you rebuild the upload?
answer
- a budget, not a bug
- six hours in any 24
- onTimeout(startId, fgsType)
- stopSelf within seconds
- a JobService on an unmetered network
basics
~20 sApps targeting Android 15 (API 35) get six hours of dataSync foreground service per 24 hours; then onTimeout(int, int) runs and the service must stop within seconds or the app crashes. Handle onTimeout and move bulk uploads to a JobScheduler job.
solid answer
~40 sOn Android 15, for apps targeting API 35, `dataSync` and `mediaProcessing` services may run six hours per 24 hours in the background, a budget shared by all services of that type and reset when the user opens the app. At the limit the system calls `onTimeout(startId, fgsType)`; the service is no longer foreground and has a few seconds to call `stopSelf()`, or the app crashes with `RemoteServiceException`. Later `dataSync` starts throw `ForegroundServiceStartNotAllowedException`. Implement `onTimeout()` to save progress and stop, then move the bulk upload to `JobScheduler`: a `JobService` guarded by `BIND_JOB_SERVICE`, a `JobInfo` requiring `NETWORK_TYPE_UNMETERED`, `onStartJob()` handing work to a thread and returning `true`, `jobFinished()` at the end, and `onStopJob()` returning `true` to reschedule. For a user-tapped upload on Android 14+, use a user-initiated data transfer job.
code
kotlin · 30 linesclass ClipUploadJobService : JobService() {
private var worker: Thread? = null
override fun onStartJob(params: JobParameters): Boolean {
worker = thread {
when (uploadPendingClips()) { // resumes from saved progress
UploadResult.DONE -> jobFinished(params, false)
UploadResult.RETRY -> jobFinished(params, true)
UploadResult.STOPPED -> Unit // onStopJob already ended it
}
}
return true // main thread returns; work continues
}
override fun onStopJob(params: JobParameters): Boolean {
worker?.interrupt()
return true // reschedule when constraints hold again
}
}
fun scheduleClipUpload(context: Context) {
val job = JobInfo.Builder(
CLIP_UPLOAD_JOB_ID,
ComponentName(context, ClipUploadJobService::class.java),
)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresCharging(true)
.build()
context.getSystemService(JobScheduler::class.java).schedule(job)
}go deeper
Know that apps targeting Android 15 get six hours of background dataSync foreground service a day, and that onTimeout() means stop now.
Explain the shared, resettable budget, the crash when onTimeout() is ignored, and the JobService contract of onStartJob(), jobFinished() and onStopJob().
Diagnose the RemoteServiceException from the timeout, make uploads resumable, and choose between a constrained job and a user-initiated data transfer job.
Treat foreground-service time as a scarce budget, and decide which transfers are user-visible jobs and which are deferrable work that must survive being stopped.
## The limit behind the crash For apps targeting **Android 15 (API 35)** or higher, the system limits how long `dataSync` and `mediaProcessing` foreground services may run while the app is in the background: - **Six hours in a 24-hour period** per type. The budget is tracked separately for `dataSync` and for `mediaProcessing`. - The budget is **shared** by all of the app's services of that type: after four hours of one `dataSync` service, a second one gets two. - It **resets** when the user brings the app to the foreground, and otherwise rolls over a 24-hour window. - When it runs out, the system calls **`Service.onTimeout(int startId, int fgsType)`** (added in API 35) and the service stops being a foreground service. - The service then has **a few seconds** to call `stopSelf()` (or `stopService()`; `stopForeground()` also works by demoting it). If it does not, the app crashes with `android.app.RemoteServiceException: "A foreground service of type dataSync did not stop within its timeout: ..."`. - Once the budget is spent, starting another `dataSync` foreground service throws `ForegroundServiceStartNotAllowedException` with a message like "Time limit already exhausted for foreground service type dataSync". `shortService` has its own, much shorter limit of about three minutes, after which a service that keeps running gets an ANR. On versions before 15, `onTimeout(int, int)` does not exist, so the service must stop itself without relying on the callback. ## Handling onTimeout The first fix is to obey the callback: save how far the upload got, then stop. ```kotlin override fun onTimeout(startId: Int, fgsType: Int) { uploader.saveProgress() stopSelf() } ``` That ends the crash but not the problem: a day of driving footage still does not fit, and the next start throws. The Android guide's advice is to start `dataSync` services only from a direct user interaction, keep them under the budget, or use another API for the transfer. ## Rebuilding the upload as a JobScheduler job Bulk, deferrable uploads fit **`JobScheduler`**, the platform scheduler that runs work when its constraints hold: 1. Build a `JobInfo` with `JobInfo.Builder(jobId, ComponentName(context, ClipUploadJobService::class.java))`, add `setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)` and, if you like, `setRequiresCharging(true)`; `setPersisted(true)` keeps it across reboots and needs `RECEIVE_BOOT_COMPLETED`. 2. Schedule it with `getSystemService(JobScheduler::class.java).schedule(job)`, which returns `RESULT_SUCCESS` or `RESULT_FAILURE`. 3. Declare the `JobService` in the manifest with `android:permission="android.permission.BIND_JOB_SERVICE"`; without it the system ignores the service. The `JobService` contract is where most bugs live: - `onStartJob()` runs on the **main thread**. Start the upload on another thread and return `true`, meaning work continues; returning `false` says the job is already finished and releases its wakelock. - When the work ends, call `jobFinished(params, wantsReschedule)`; `true` asks for a retry under the back-off policy. - If the constraints stop holding (Wi-Fi drops, the charger is unplugged), the system calls `onStopJob()`; stop the upload and return `true` to have the job rescheduled. `JobParameters.getStopReason()` says why. You need not call `jobFinished()` after `onStopJob()`. - Since Android 14, failing to return from `onStartJob()` or `onStopJob()` within several seconds triggers an ANR. - The system holds a wakelock for the job, and jobs may be stopped after about 10 minutes when the system needs resources, so long uploads must resume from saved progress. ## When the user taps Upload now For a transfer the user explicitly starts, Android 14 (API 34) added **user-initiated data transfer jobs**: `setUserInitiated(true)` plus a required network, the `RUN_USER_INITIATED_JOBS` permission, scheduled while the app is in the foreground or allowed to start an activity, and a notification supplied with `JobService.setNotification()` within 10 seconds of `onStartJob()`. They are exempt from ordinary job quotas. Since Android 16, jobs started from a foreground service follow normal quotas, so wrapping a job in a `dataSync` service no longer buys runtime. | Option | Fits | Limit | |---|---|---| | `dataSync` foreground service | user-started, bounded transfer | 6 h per 24 h on Android 15 | | `JobService` with constraints | bulk uploads on Wi-Fi | job quotas, possible 10-minute stops | | User-initiated data transfer job | a large transfer the user tapped | scheduled only from the foreground | The guide also points to WorkManager, which runs on top of `JobScheduler`; it is covered in its own lesson. ## Testing without waiting six hours On an Android 15 device, `adb shell am compat enable FGS_INTRODUCE_TIME_LIMITS <package>` turns the limit on even for an older target, and `adb shell device_config put activity_manager data_sync_fgs_timeout_duration <ms>` shortens it.
- The driver taps Upload trip now for 4 GB of clips. Which mechanism fits?A user-initiated data transfer job, added in Android 14: `setUserInitiated(true)` with a required network, the `RUN_USER_INITIATED_JOBS` permission, scheduled while the app is in the foreground, and a notification set with `JobService.setNotification()` within 10 seconds of `onStartJob()`. It is exempt from the usual job quotas and is not bound by the `dataSync` six-hour budget.
- Can the app keep the dataSync service and start the job from inside it to dodge job quotas?Not from Android 16 on. Since API 36, jobs started from a foreground service must follow their normal runtime quotas, whether they are scheduled directly with `JobScheduler` or through a library built on it. The service no longer buys the job extra runtime.
- How do you reproduce the timeout in a test without waiting six hours?On an Android 15 device run `adb shell am compat enable FGS_INTRODUCE_TIME_LIMITS <package>` to turn the limit on even for an older target, then `adb shell device_config put activity_manager data_sync_fgs_timeout_duration <ms>` to shorten it, and check that `onTimeout()` saves progress and stops.
- The six-hour dataSync limit applies to each service separately.
- Calling startForeground() again inside onTimeout() renews the six-hour budget.
- A JobService's onStartJob() runs on a background thread, so it can upload inline.
- Returning false from onStartJob() keeps the job running until jobFinished().
- Switching the service to the shortService type gives the upload more time.
Assumes targetSdk 35+ on Android 15 (API 35), which added the dataSync and mediaProcessing time limits and onTimeout(int, int); user-initiated jobs are Android 14 (API 34); checked against the API 37 sources.