A Context, activity, fragment or view is kept in a static property, which leaks it

tx0/kotlin:static-context-referencestrictwarningframeworks/androiddepth fastbug, android

What it finds

A property of a companion object, an object or the top level lives as long as the process. When it holds an activity, a fragment, a view or a context other than the application's, that object and everything it references can never be collected after the screen closes. A weak reference, or the application context, avoids the leak.

From the rule's source, static_context.rs.

Example from the rule's tests
class App : Application() {    companion object {        lateinit var activity: MainActivitytx0 reports: activity keeps a MainActivity        var context: Context? = nulltx0 reports: context keeps a Context        var model: ViewModel? = null        var ref: WeakReference<Activity>? = null    }} object Holder {    var view: TextView? = nulltx0 reports: view keeps a TextView} class Screen {    var view: View? = null}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:static-context-reference" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:static-context-reference] reason="..."

tx0 explain tx0/kotlin:static-context-reference shows the same in the terminal. Found a false positive? Report it.