Skip to content

Migrate snippets Background work - #1119

Open
barbaralaw wants to merge 11 commits into
android:mainfrom
StellarElements:bg-work-snippet-migration
Open

barbaralaw wants to merge 11 commits into
android:mainfrom
StellarElements:bg-work-snippet-migration

Conversation

@barbaralaw

@barbaralaw barbaralaw commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Extracts the Kotlin samples from four background-work guides into :backgroundwork (com.example.snippets.backgroundwork) as region-tagged source, so the guides can import them instead of hardcoding them. Wake-lock samples for the same DAC area already live in that module.

20 snippets across 4 pages. 16 publish exactly what the page shows. 4 differ, every one listed below with a reason. Line wrapping is not counted as a difference: spotlessApply runs before submission and rewraps long calls without changing what a reader reads.

Region tags all begin android_background_; the tables drop that prefix.

How to read the "why" column

Why What a reader of the page would see
// ... The page prints a standalone ..., which Kotlin will not compile. The region publishes // ... as a line comment.
hardcoded snippet defect fixed The published Kotlin does not compile, and this is not a sample meant to demonstrate an error. The region publishes the corrected line.

Per page

1. Keep the screen on

https://developer.android.com/develop/background-work/background-tasks/awake/screen-on

1 snippet, all 1 match as published: awake_screen_on.

MainActivity is registered in this module’s manifest (MAIN / LAUNCHER). setContentView(R.layout.activity_main) inflates a compile-only FrameLayout stub in :backgroundwork; that layout is not a published region.

2. System restrictions on background tasks

https://developer.android.com/develop/background-work/background-tasks/bg-work-restrictions

2 snippets, 1 match, 1 differ.

Snippet Page section Difference Why
restrictions_worker_triggered_content Determine which content authorities triggered work Adds the missing class-body {; private val params so params.triggeredContentAuthorities / params.triggeredContentUris compile hardcoded snippet defect fixed

Matching as published: restrictions_schedule_work.

3. Testing Worker implementation

https://developer.android.com/develop/background-work/background-tasks/testing/persistent/worker-impl

8 snippets, all 8 match as published: testing_sleep_worker_basic, testing_sleep_worker_test_basic, testing_sleep_worker_input_data, testing_sleep_worker_test_input_data, testing_coroutine_worker, testing_coroutine_worker_test, testing_rx_worker, testing_rx_worker_test.

These snippets live in :backgroundwork androidTest. Catalog aliases androidx-work-testing and androidx-work-rxjava2 share version.ref = "androidx-work-runtime" and are androidTestImplementation, with androidx.test.ext:junit / core / runner on the same configuration. Comments outside the regions note that each SleepWorker would normally live in src/main.

4. Schedule alarms

https://developer.android.com/develop/background-work/services/alarms

9 snippets, 6 match, 3 differ.

Snippet Page section Difference Why
alarms_cancel_service Set a repeating alarm PendingIntent.FLAG_NO_CREATE or FLAG_IMMUTABLE instead of FLAG_NO_CREATE alone hardcoded snippet defect fixed
alarms_elapsed_realtime_one_time Examples of elapsed real time alarms // ... for the page’s ...; getBroadcast(..., FLAG_IMMUTABLE) instead of flag 0; var / lateinit var instead of private var / private lateinit // ..., hardcoded snippet defect fixed
alarms_rtc_repeating_precise Examples of real time clock alarms same as one-time elapsed // ..., hardcoded snippet defect fixed

Matching as published: alarms_boot_receiver, alarms_elapsed_realtime_repeating, alarms_rtc_repeating, alarms_cancel_direct, alarms_enable_receiver, alarms_disable_receiver.

The one-time elapsed and precise RTC samples live in a compile-only fun schedule() so every published line is at function-body indent (ktlint and the rendered block stay aligned). Locals cannot be private, so those two modifiers are dropped; alarm behavior is unchanged.

From API 31 a PendingIntent must set FLAG_IMMUTABLE or FLAG_MUTABLE; these samples do not need a mutable intent.

Not extracted

Kotlin only. Blocks that are not Kotlin samples stay on the page; each kind has a verdict below.

Keep the screen on

  • Java twin of awake_screen_on — remove with the page edit that retires Java.
  • Layout XML (RelativeLayout with android:keepScreenOn="true") — keep hardcoded. It was not given a region tag.

System restrictions on background tasks

No unclaimed blocks. Both Kotlin samples are extracted.

Testing Worker implementation

  • Java twins (SleepWorker / SleepWorkerTest / RxWorker, six blocks) — remove with the page edit that retires Java.

Schedule alarms

  • Java twins of the extracted Kotlin samples — remove with the page edit that retires Java.
  • Manifest XML (SCHEDULE_EXACT_ALARM / USE_EXACT_ALARM, RECEIVE_BOOT_COMPLETED, boot receiver) — keep hardcoded. Manifest samples sit outside /build/.
  • Definition-list API names under Use cases that might not require exact alarms and Ways to set an exact alarm (Handler.postAtTime, WorkManager, setAndAllowWhileIdle, set, setWindow, setExact, setExactAndAllowWhileIdle, setAlarmClock) — out of scope. They are prose API lists, not copy-paste Kotlin samples.

Live snippet fixes this surfaced

  1. System restrictions: MyWorker is missing { after the constructor. Constructor params is not a property, so params.triggeredContentAuthorities / params.triggeredContentUris in doWork would not compile. The region adds private val params and keeps those WorkerParameters calls.
  2. Schedule alarms: PendingIntent.getService / getBroadcast without a mutability flag (FLAG_NO_CREATE alone, or 0). Invalid from API 31.

Verification

  • ./gradlew :backgroundwork:compileDebugKotlin — passes
  • ./gradlew :backgroundwork:compileDebugAndroidTestKotlin — passes
  • ./gradlew :backgroundwork:lintDebug — passes
  • ./gradlew spotlessApply — run before submitting; the branch is clean afterwards

@google-cla

google-cla Bot commented Sep 18, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@barbaralaw
barbaralaw force-pushed the bg-work-snippet-migration branch from 603bead to 4dbfefe Compare September 22, 2026 21:50
@barbaralaw
barbaralaw marked this pull request as ready for review September 22, 2026 21:55
@snippet-bot

snippet-bot Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 20 region tags.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@kkuan2011 kkuan2011 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you run spotless to confirm it passes successfully?

Spotless / ktlint indentation & straddled region tags (android_background_alarms_elapsed_realtime_one_time & android_background_alarms_rtc_repeating_precise):

In both ElapsedRealtimeOneTimeSnippet (lines 48–50) and RtcRepeatingPreciseSnippet (lines 70–72), the class-level properties private var alarmMgr: AlarmManager? = null and private lateinit var alarmIntent: PendingIntent are indented by 8 spaces (instead of 4 spaces) so they visually align with statements inside fun schedule(), while [START ...] opens at class scope and [END ...] closes inside fun schedule().

Running ./gradlew :backgroundwork:spotlessCheck (ktlint) flags 8-space indentation on class-level properties (or spotlessApply de-indents them to 4 spaces, misaligning the rendered snippet).

To keep both spotlessApply and the rendered DAC indentation clean, please move [START ...] inside fun schedule() (or declare var alarmMgr: AlarmManager? = null and lateinit var alarmIntent: PendingIntent as local variables/comments inside fun schedule()) and verify ./gradlew :backgroundwork:spotlessApply passes cleanly.

@kkuan2011 kkuan2011 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great!

Comment thread backgroundwork/build.gradle.kts Outdated

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants