Android CI 中以 Lint、R8 和資源縮減器追查無用程式碼與資源
The Ratchet and the Report: Hunting Dead Code in Android CI
文章示範如何在 Android CI 中結合 Lint、R8 報告及資源縮減器,建立逐步收緊的門檻,持續追蹤並清理無用程式碼與資源。做法包括比較 Lint 基線條目,並為 R8 移除的類別及未使用資源設定預算;縮減後的建置和測試則有助檢查反射等動態引用風險。可選的 AI 步驟只根據工具報告提出 PR 建議,並須經 JSON 驗證、建置和測試,再由人員審核合併。
Every long-lived Android codebase accumulates code that nobody calls and resources that nothing references. It starts innocently: an A/B test ends but its layouts stay, a feature flag is retired but its three fallback classes remain, and a design refresh leaves 40 orphaned drawables behind. None of it breaks the build, so none of it gets removed.
This post builds a CI setup that turns dead-code removal from a quarterly cleanup into a continuous, enforced property of the repository. We will combine three signals (Lint, R8 reports, and the resource shrinker), wire them into gates that can only tighten over time, and finish with an optional, carefully fenced AI step that drafts removal suggestions. Along the way we will look at the failure modes that bite in production, because dead-code tooling fails in ways that are quiet until a release build crashes.
The examples use a fictional grocery-delivery app called Harbor (com.harbor.shop).
Three detectors, three different questions
Before configuring anything, be clear about what each tool actually knows. They are not redundant. Each one answers a different question at a different layer.
The practical consequence: Lint tells you what to delete from source, R8 tells you what the compiler already proved unreachable, and the resource shrinker tells you what ships in the APK but should not. A gate built on only one of them leaves a gap the others would have covered.
1. Lint baselines: adopt strictness without a rewrite
If you turn on UnusedResources in a five-year-old project, you will get hundreds of findings on day one. A baseline lets you accept that debt explicitly and fail only on new problems.
Configuration
// app/build.gradle.kts
android {
lint {
baseline = file("lint-baseline.xml")
// Analyze library modules together with :app so a resource used only
// from :app is not reported as unused inside the library.
checkDependencies = true
abortOnError = true
warningsAsErrors = false // keep unrelated warnings from blocking
checkReleaseBuilds = false // CI runs lint explicitly; don't pay twice
enable += setOf("UnusedResources", "UnusedIds")
error += setOf("UnusedResources") // promote to build-breaking
htmlReport = true
xmlReport = true
sarifReport = true // consumable by code-scanning UIs
}
}
Create or refresh the baseline with:
./gradlew :app:updateLintBaseline
Failure mode: the baseline becomes a graveyard
A baseline file is easy to regenerate, and that is the problem. The first time a PR goes red because of a new unused resource, someone runs updateLintBaseline, commits the result, and CI turns green. The finding has not been fixed, only hidden. Repeat this a few dozen times and the baseline grows instead of shrinking.
The fix is a ratchet: CI compares the PR’s baseline to the one on the target branch and fails if the entry count increased.
// buildSrc or a convention plugin
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import java.io.File
abstract class LintBaselineRatchet : DefaultTask() {
@get:InputFile
abstract val baseline: RegularFileProperty
/** Baseline from the target branch. Absent on the very first run. */
@get:InputFile
@get:Optional
abstract val reference: RegularFileProperty
@TaskAction
fun verify() {
val now = countEntries(baseline.get().asFile)
val before = reference.orNull?.asFile?.let(::countEntries) ?: return
check(now <= before) {
"Lint baseline grew from $before to $now entries. " +
"Fix the new findings instead of baselining them."
}
logger.lifecycle("Lint baseline entries: $before -> $now")
}
private fun countEntries(file: File): Int =
Regex("<issue\\b").findAll(file.readText()).count()
}
// app/build.gradle.kts
tasks.register<LintBaselineRatchet>("lintBaselineRatchet") {
baseline.set(layout.projectDirectory.file("lint-baseline.xml"))
reference.set(providers.gradleProperty("baselineRef").map { layout.projectDirectory.file(it) })
}
More baseline gotchas
- Renames resurrect findings. Lint matches baseline entries on issue ID, message, and file path rather than exact line numbers, so edits that shift lines are fine, but moving or renaming a file makes its old findings look new. Treat large package moves as a deliberate “regenerate baseline” PR, reviewed on its own, with the ratchet temporarily comparing against the new count.
- Tool upgrades change the findings. An AGP or Lint upgrade can add checks or alter messages. Do the upgrade and the baseline refresh in one dedicated PR; never mix it with feature work.
- Per-module baselines drift apart. If you run Lint per module, give each its own baseline and ratchet each one. A single shared baseline hides which module is decaying.
2. shrinkResources: let the build prove what is unused
Lint reasons about source. The resource shrinker works on the built app, so it can also see what R8 removed. Code that R8 drops no longer references its resources, which makes those resources removable.
// app/build.gradle.kts
android {
buildTypes {
release {
isMinifyEnabled = true // required: the shrinker depends on R8's result
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
}
}
After a release build, look in app/build/outputs/mapping/release/. In recent AGP versions you will find usage.txt (code R8 removed) and resources.txt (what the resource shrinker kept or dropped) next to mapping.txt. Those files are your raw evidence. Confirm the exact set for your AGP version by listing the directory once; don't assume.
Failure mode: dynamic lookups that the shrinker cannot see
Harbor shows a promo banner whose drawable is chosen from a server-provided slot name:
// Fragile: the resource name is assembled at runtime
@SuppressLint("DiscouragedApi") // lint warns about getIdentifier for exactly this reason
fun promoBanner(context: Context, slot: String): Drawable? {
val id = context.resources.getIdentifier("promo_$slot", "drawable", context.packageName)
return if (id != 0) AppCompatResources.getDrawable(context, id) else null
}
Because this code calls getIdentifier, the shrinker's default (safe) mode treats string constants that look like resource names as possible references, so it conservatively keeps drawables starting with promo_. Nothing breaks, but those drawables are never shrunk. A well-meaning engineer then enables strict mode to claw back size, and now promo_summer.png is gone. The result is a null banner in production with no crash and nothing in your own logs, just a quietly empty slot.
Make the references visible instead:
// Robust: the compiler and shrinker both see every resource
private val promoBanners: Map<String, Int> = mapOf(
"summer" to R.drawable.promo_summer,
"winter" to R.drawable.promo_winter,
"launch" to R.drawable.promo_launch,
)
fun promoBanner(context: Context, slot: String): Drawable? =
promoBanners[slot]?.let { AppCompatResources.getDrawable(context, it) }
An explicit map costs a few lines and makes the dependency greppable, lintable, and shrinkable. If a dynamic lookup is truly unavoidable, declare it:
<!-- res/raw/keep.xml -->
<resources xmlns:tools="http://schemas.android.com/tools"
tools:shrinkMode="strict"
tools:keep="@drawable/promo_*"
tools:discard="@layout/debug_overlay_*" />
Other resource-shrinking surprises
-
Library modules do not shrink resources.
isShrinkResourcesis configured on the application build; dynamic features are shrunk as part of the base app's configuration rather than on their own. An unused drawable in:design-systemwill ship unless Lint'sUnusedResourceswithcheckDependencies = truecatches it. - Placeholder versus removal. Depending on the AGP version and settings, unused resources may be replaced by tiny stubs so resource IDs stay stable, rather than deleted outright. Verify the real size effect in Android Studio’s APK Analyzer instead of trusting the build log.
-
Reflection-loaded layouts. Layouts inflated by name from a string (common in legacy plugin systems) need the same treatment as
getIdentifier.
3. R8 reports: turn “removed code” into a metric
R8’s usage.txt lists classes and members it removed as unreachable. For a shipped release, that is a free dead-code inventory. Whole classes listed there are strong candidates for deletion from source, because nothing reaches them from any entry point.
Here is a small Gradle task that reads usage.txt, filters to Harbor's own packages, and fails if the number of fully removed classes exceeds a budget:
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
abstract class R8DeadClassReport : DefaultTask() {
/** mapping.txt; its producer task is tracked, usage.txt sits beside it. */
@get:InputFile
abstract val mappingFile: RegularFileProperty
@get:Input
abstract val ownPackages: ListProperty<String>
@get:Input
abstract val maxDeadClasses: Property<Int>
@get:OutputFile
abstract val report: RegularFileProperty
@TaskAction
fun run() {
val prefixes = ownPackages.get()
// usage.txt: unindented lines name classes. A trailing ':' means only
// some members were removed; no colon means the whole class was dropped.
val usage = mappingFile.get().asFile.resolveSibling("usage.txt")
check(usage.exists()) {
"usage.txt not found next to mapping.txt (${usage.parent}). Did R8 run for this variant?"
}
val classLines = usage.useLines { lines ->
lines
.filter { it.isNotEmpty() && !it.first().isWhitespace() }
.filter { line -> prefixes.any { p -> line.startsWith(p) } }
.toList()
}
val (partial, whole) = classLines.partition { it.endsWith(":") }
val byPackage = whole
.groupingBy { it.substringBeforeLast('.', missingDelimiterValue = "(default)") }
.eachCount()
.toList()
.sortedByDescending { (_, count) -> count }
report.get().asFile.apply {
parentFile.mkdirs()
writeText(buildString {
appendLine("Fully removed classes: ${whole.size}")
appendLine("Classes with removed members: ${partial.size}")
appendLine()
byPackage.forEach { (pkg, n) -> appendLine("%4d %s".format(n, pkg)) }
})
}
check(whole.size <= maxDeadClasses.get()) {
"R8 removed ${whole.size} of our own classes (budget ${maxDeadClasses.get()}). " +
"Delete the dead code or justify a keep rule."
}
}
}
// app/build.gradle.kts
import com.android.build.api.artifact.SingleArtifact
androidComponents {
onVariants(selector().withBuildType("release")) { variant ->
// Skip variants that are not minified: no R8 run means no usage.txt to read.
if (!variant.isMinifyEnabled) return@onVariants
// Declaring mapping.txt as the task input keeps the R8 producer task attached.
// R8 writes usage.txt (and the shrinker resources.txt) beside it.
val mapping = variant.artifacts.get(SingleArtifact.OBFUSCATION_MAPPING_FILE)
val suffix = variant.name.replaceFirstChar { it.uppercase() } // "Release", "FreeRelease"...
tasks.register<R8DeadClassReport>("r8DeadClassReport$suffix") {
mappingFile.set(mapping)
ownPackages.set(listOf("com.harbor.shop"))
maxDeadClasses.set(providers.gradleProperty("deadClassBudget").map(String::toInt).orElse(25))
report.set(layout.buildDirectory.file("reports/dead-code/r8-dead-classes-$suffix.txt"))
}
// Gate 3 (see section 4)
if (variant.shrinkResources) {
tasks.register<UnusedResourceReport>("unusedResourceReport$suffix") {
mappingFile.set(mapping)
// Only orders tasks when both are requested, e.g. `assembleRelease unusedResourceReportRelease`
mustRunAfter(tasks.matching { it.name == "assemble$suffix" })
maxUnused.set(providers.gradleProperty("unusedResourceBudget").map(String::toInt).orElse(60))
}
}
}
}
Registering through the Variant API (instead of dependsOn("minifyReleaseWithR8")) avoids hardcoding an internal task name, and it produces one task per release variant when you use flavors. variant.isMinifyEnabled needs AGP 7.4 or newer, and variant.shrinkResources is newer still (AGP 8.1 or later, as far as I can tell). On older AGP versions, delete the if (variant.shrinkResources) wrapper and rely on the task's own resources.txt existence check. Verify both properties against your AGP version, since I have not compiled this. Store deadClassBudget in gradle.properties and lower it each time a cleanup lands. This is the same ratchet idea as the Lint baseline: the number is allowed to fall, never rise.
Failure mode: one broad keep rule disables the whole signal
# Looks harmless. Silently turns off shrinking for the entire package tree.
-keep class com.harbor.shop.** { *; }
With this in place, usage.txt contains nothing from your own code, your dead-class count reads zero, and your gate passes forever. The signal has been switched off, not satisfied. Audit your rules the same way you audit the report:
- Compare
configuration.txtagainst the rules you think you wrote, because library consumer rules are merged in and can be broader than expected. - Narrow keeps to the smallest scope that works:
# Only the serialized fields, only in the DTO package
-keepclassmembers class com.harbor.shop.api.dto.** {
@com.google.gson.annotations.SerializedName <fields>;
}
Failure mode: the code R8 removes is code you reach by name
Harbor loads payment handlers through a string from remote config:
// Fragile: R8 cannot see this constructor call
fun handlerFor(provider: String): PaymentHandler =
Class.forName("com.harbor.shop.payments.${provider.replaceFirstChar(Char::titlecase)}Handler")
.getDeclaredConstructor()
.newInstance() as PaymentHandler
R8 can follow Class.forName only when the argument is a compile-time constant. Here the name is assembled from runtime input, so R8 sees no static reference to UpiHandler, removes it, and the release build throws ClassNotFoundException the first time a user picks UPI. Debug builds never show it because they are not shrunk. This class of bug is the main reason teams distrust dead-code tooling, and it is why the report must be treated as evidence to review, not a to-do list to apply blindly.
The idiomatic repair is to make reachability explicit, which also makes the code easier to test:
private val handlers: Map<String, () -> PaymentHandler> = mapOf(
"upi" to ::UpiHandler,
"card" to ::CardHandler,
"wallet" to ::WalletHandler,
)
fun handlerFor(provider: String): PaymentHandler =
handlers[provider]?.invoke() ?: error("Unknown payment provider: $provider")
Constructor references are visible to R8, so these classes are kept when, and only when, the map is reachable.
Two more traps worth a test each:
-
Release-only code paths. Run your instrumented smoke tests against a minified build (a
release-like variant with the debug signing key) so reflection failures show up before users see them. -
Debug-only classes inflate the report. Classes used only in debug builds legitimately vanish from release. Exclude
*.debug.*packages fromownPackagesor the budget will be noisy and people will stop trusting it.
4. CI gates: cheapest first, tightest last
Individually, these checks are advice. A gate makes them policy. The order below runs Lint first, because it needs no minified build. Lint is not instant on a large multi-module project, so run lintDebug (the baseline file is shared across variants) rather than lintRelease, and add incremental or per-module runs if it gets slow. The two R8-derived gates need a minified build, so they come after.
Gate 3 reads resources.txt and counts resources the shrinker judged unreachable:
abstract class UnusedResourceReport : DefaultTask() {
@get:InputFile
abstract val mappingFile: RegularFileProperty
@get:Input
abstract val maxUnused: Property<Int>
@TaskAction
fun run() {
val file = mappingFile.get().asFile.resolveSibling("resources.txt")
check(file.exists()) { "resources.txt not found at ${file.path}. Run assembleRelease first." }
// Classic shrinker dump: one "@type/name : reachable=true|false" line per resource.
// Other AGP versions or optimized resource shrinking may format this differently.
var reachable = 0
var unused = 0
file.forEachLine { line ->
when {
"reachable=false" in line -> unused++
"reachable=true" in line -> reachable++
}
}
// Fail loudly if the format is not recognized, instead of passing with a count of zero.
check(reachable + unused > 0) {
"No reachable=true/false entries in ${file.name}; update the parser for your AGP version."
}
check(unused <= maxUnused.get()) {
"Resource shrinker found $unused unreachable resources (budget ${maxUnused.get()}). " +
"Remove them or add a documented tools:keep."
}
}
}
resources.txt is written by the resource shrinker, not by R8, so the task reads it by location rather than through a tracked output. Run assembleRelease first, as the workflow below does. Running this task on its own triggers R8 but not the resource shrinker, so it stops with the "resources.txt not found" message. The mustRunAfter above makes ./gradlew assembleRelease unusedResourceReportRelease safe in a single command. An unsigned release build is fine for this: with no signing config, AGP simply produces an unsigned APK.
# .github/workflows/dead-code-gates.yml
name: dead-code-gates
on:
pull_request:
branches: [main]
concurrency:
group: dead-code-${{ github.ref }}
cancel-in-progress: true
jobs:
gates:
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- uses: gradle/actions/setup-gradle@v4
- name: Fetch target-branch baseline
run: git show origin/${{ github.base_ref }}:app/lint-baseline.xml > "$RUNNER_TEMP/base-baseline.xml"
- name: Gate 1 - Lint and baseline ratchet
run: >
./gradlew :app:lintDebug :app:lintBaselineRatchet
-PbaselineRef="$RUNNER_TEMP/base-baseline.xml"
- name: Build minified release (unsigned is fine)
run: ./gradlew :app:assembleRelease
- name: Gate 2 - R8 dead-class budget
run: ./gradlew :app:r8DeadClassReportRelease
- name: Gate 3 - Unused resource budget
run: ./gradlew :app:unusedResourceReportRelease
- name: Upload evidence
if: always()
uses: actions/upload-artifact@v4
with:
name: dead-code-reports
path: |
app/build/reports/lint-results-debug.html
app/build/reports/lint-results-debug.sarif
app/build/reports/dead-code/
app/build/outputs/mapping/release/usage.txt
app/build/outputs/mapping/release/resources.txt
CI failure modes to plan for
- Flaky verdicts from cold caches. If Lint results differ between a warm and a cold runner, engineers learn to re-run until green. Pin the JDK and AGP versions, and keep the Gradle cache enabled, so the same commit yields the same verdict.
-
The branch has no baseline yet.
git showfails iflint-baseline.xmldoes not exist on the target branch. Handle that case once (for example, by committing an initial baseline onmainfirst) rather than letting the step silently skip. - Signing blocks release builds on PRs. You do not need a signed artifact to get R8 output. Build an unsigned or debug-signed minified variant so PRs from contributors without secrets still produce reports.
-
A gate no one can explain gets bypassed. Make failure messages say what to do (the
checkmessages above do), and attach the reports to the run so the reviewer does not have to rebuild locally. - Budgets need an owner. A ratchet that only tightens will eventually block an unrelated urgent fix. Define who may raise a number, and require a written reason in the PR when they do.
5. Optional: AI-generated PR suggestions
Once you have reliable evidence files, a language model can help with the tedious part: reading the findings, locating the symbol, and drafting a removal diff with an explanation. This is optional and should be advisory. The model should never be the thing that decides something is dead.
Design principles
- Ground the model in evidence. The prompt contains only the Lint/R8/resource findings and the minimum surrounding code. The model may propose removing a symbol only if that symbol already appears in a report.
- Require structured output. Free-form prose is unverifiable. Ask for JSON and reject anything that does not parse.
- Verify with the build, not with the model. A suggestion is posted only after the proposed change compiles, builds a minified variant, and passes tests in a scratch worktree.
- Keep a human in the merge path. Post suggestions as PR comments. Do not push commits.
A typed contract keeps the model’s output honest:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
enum class SymbolKind { CLASS, FUNCTION, RESOURCE }
@Serializable
data class RemovalProposal(
val path: String,
val symbol: String,
val kind: SymbolKind,
val evidence: List<String>, // report lines that justify removal
val rationale: String,
)
private val strictJson = Json { ignoreUnknownKeys = false }
fun parseProposals(raw: String): List<RemovalProposal> =
try {
strictJson.decodeFromString(raw)
} catch (e: IllegalArgumentException) {
// SerializationException is a subclass, and some validation failures
// surface as plain IllegalArgumentException. Malformed output is
// discarded, never "repaired".
emptyList()
}
/** A proposal survives only if the tools already flagged the symbol. */
fun List<RemovalProposal>.grounded(
reportedDead: Set<String>,
keepRules: List<Regex>,
): List<RemovalProposal> = filter { p ->
p.evidence.isNotEmpty() &&
p.symbol in reportedDead &&
keepRules.none { rule -> rule.containsMatchIn(p.symbol) }
}
The final filter is the important line. It means a hallucinated symbol, or a real symbol the tools did not flag, is dropped before anyone sees it.
AI failure modes
-
Confident wrong answers on reflective code. A model reading
handlerForabove may concludeUpiHandleris unused. The grounding filter plus a minified-build smoke test is what catches this, not a better prompt. - Prompt injection through the repository. Source comments, string resources, and PR descriptions are attacker-controlled text. Give the model no tools, no network, and no secrets, and treat its output as untrusted data to be parsed, never as commands to be executed.
- Leaking proprietary code. Send findings and the smallest necessary snippets, not the repository. Redact tokens and keys before building the prompt, and check your provider’s data-retention terms.
- Fork PRs and credentials. Running the AI job on code from forks with access to API keys is an exfiltration risk. Restrict it to same-repository PRs:
ai-suggestions:
needs: gates
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write # comment only; no contents: write
- Noise and cost. Cap the number of suggestions per PR and skip the job when the diff does not touch files in the reports. A bot that comments on everything gets muted within a week.
A rollout that survives contact with a real team
- Week 1: Enable the Lint config, generate the baseline, and merge it with the ratchet task, warning-only.
- Week 2: Upload the R8 and resource reports as CI artifacts without gating. Look at the numbers and delete the obvious dead classes.
- Week 3: Turn the Lint ratchet into a required check. Set the dead-class and unused-resource budgets to their current counts.
- Ongoing: Lower the budget whenever a cleanup lands. Add the AI step only after the gates have been stable for a while, and keep it advisory.
Takeaways
- Lint, R8, and the resource shrinker look at source, bytecode, and APK respectively. Use all three, because each one’s blind spot is another’s strength.
- A baseline is only safe with a ratchet. Without one, it quietly becomes the place where problems go to be forgotten.
- A broad
-keeprule does not satisfy a dead-code gate. It switches the gate off. - Replace name-based lookups (
Class.forName,getIdentifier) with explicit maps of constructor and resource references. The code becomes shrinkable, testable, and greppable. - Treat every report as evidence for review, and verify with a minified build before deleting anything that might be reached by reflection.
- If you add AI, let it draft and let the build verify. The model proposes, the tools ground it, and a person merges.
📡 From Working API Calls to Real-Time, Resilient, Production-Ready Networking
Getting data from a server is only the start. Shipping an app that stays fast, secure and reliable on flaky mobile networks is the hard part. I highly recommend “Android Networking Unblocked, Volume 2: Real-Time, Reliability and Production.” It covers WebSockets, Server-Sent Events, gRPC streaming, GraphQL with Apollo, and resumable uploads. It also covers retries and error modeling, network-aware UX, and the production essentials: security, performance, testing and observability. The capstone ties it all together. Interview corner boxes and code-review checklists in every chapter make it as useful for interview prep as it is for building. The appendices give you status codes, headers, copy-ready configurations, migration guides and a production readiness checklist.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover
來源:DEV Community · dev.to




