Sub topic 13
Working with the Activity and plugin lifecycle on Android
Prerequisites and the two lifecycles
This chapter assumes that you can build a Flutter plugin, read basic Kotlin, and understand MethodChannel. You should also know that Android Activity objects represent screens and can be destroyed and recreated during configuration changes, such as screen rotation.
A Flutter plugin has two related lifecycles:
- The engine lifecycle begins when Flutter attaches the plugin to a
FlutterEngine. Use it to create the channel and access application-wide services. - The Activity lifecycle begins when the plugin attaches to an Android
Activity. Use it only for UI work, permissions, intents, or APIs that require a current screen.
An engine can continue running when no Activity is attached. For example, a Flutter engine may remain alive while the app is in the background.
Implementing `ActivityAware`
Implement ActivityAware when native code needs the current Activity. Store the Activity only while it is attached. Never assume that an Activity exists just because the plugin is attached to the engine.
package com.example.battery_info
import android.app.Activity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class ActivityInfoPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel
private var activity: Activity? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "activity_info")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(
call: MethodCall,
result: MethodChannel.Result
) {
when (call.method) {
"hasActivity" -> result.success(activity != null)
"getActivityPackage" -> {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "No Activity is attached.", null)
} else {
result.success(currentActivity.packageName)
}
}
else -> result.notImplemented()
}
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
}
override fun onReattachedToActivityForConfigChanges(
binding: ActivityPluginBinding
) {
activity = binding.activity
}
override fun onDetachedFromActivity() {
activity = null
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
activity = null
}
}The two configuration-change callbacks are important. Android destroys the old Activity and creates a new one. Clearing the old reference prevents the plugin from using a destroyed screen. Reassigning the new reference restores Activity-dependent features.
| Callback | Meaning | Typical action |
|---|---|---|
| `onAttachedToEngine` | The plugin has an engine | Create channels and services |
| `onAttachedToActivity` | A current Activity is available | Store the Activity and register listeners |
| `onDetachedFromActivityForConfigChanges` | The Activity will be recreated | Remove Activity-specific references |
| `onDetachedFromActivity` | No Activity is available | Stop UI-dependent work |
| `onDetachedFromEngine` | The engine is shutting down | Remove handlers and release resources |
Common lifecycle errors
A plugin can fail when it calls activity!! while the app is backgrounded or before the Activity has attached. Return a clear error such as NO_ACTIVITY instead. Also unregister permission, activity-result, and lifecycle listeners when the Activity detaches. Registering the same listener again after every configuration change can otherwise produce duplicate callbacks.
Exercise
Why must a plugin implement both onDetachedFromActivityForConfigChanges and onDetachedFromActivity?
Show answer
The first handles temporary Activity replacement during configuration changes, while the second handles a permanent loss of the Activity. Both callbacks must clear Activity-specific references.