Android Super Lifecycle

ID

kotlin.android_super_lifecycle

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

android, reliability

Description

Reports Android lifecycle method overrides that do not call their super counterpart correctly. Android Activity, Fragment, Service, and BroadcastReceiver subclasses are required by the framework to forward init callbacks (onCreate, onStart, onResume, onRestart, onAttach, onActivityCreated, onCreateView, onViewCreated) as the first statement, and teardown callbacks (onPause, onStop, onDestroy, onDestroyView, onDetach) as the last statement. Missing or mis-ordered super calls cause hard-to-diagnose state corruption, leaked resources, and SuperNotCalledException crashes.

Rationale

class MyActivity : Activity() {
    override fun onCreate(b: Bundle?) {       // FLAW — no super.onCreate
        setContentView(0)
    }

    override fun onStart() {
        super.onStart()                       // OK — first statement
        init()
    }

    override fun onStop() {
        cleanup()
        super.onStop()                        // OK — last statement
    }
}

The rule scans every class whose superclass is a known Android component (Activity, Fragment, Service, …​), then for each lifecycle override checks that super.X(…​) is called somewhere in the body and that it appears at the correct position for the init / teardown family.

Remediation

  • Add super.X(…​) as the first statement of every init override.

  • Add super.X(…​) as the last statement of every teardown override.

  • Forward all parameters: override fun onCreate(b: Bundle?) { super.onCreate(b); …​ }.

  • When refactoring, do not silently drop the super call to "speed up" the method.