Sub topic 13
Working with the Activity and plugin lifecycle on Android
This chapter assumes you have written the Kotlin side of a plugin with FlutterPlugin and MethodCallHandler, as in the earlier Android chapter. You should also know what an Android Activity is and how startActivityForResult works.
The battery example needed only an application Context, which exists for the whole life of the process. Many native features need more than that. Showing a system picker, asking for a runtime permission, or reading the launch Intent all require an Activity. An Activity can be destroyed and recreated while your plugin is still alive, so holding one in a field the wrong way causes leaks and crashes.
Two lifecycles, not one
A plugin has two separate lifecycles.
- Engine lifecycle.
onAttachedToEngineandonDetachedFromEnginerun when the plugin is added to or removed from aFlutterEngine. TheFlutterPluginBindinggives you theapplicationContextand thebinaryMessenger. - Activity lifecycle. A plugin that also implements
ActivityAwareis told when the engine gets attached to an Activity and when that Activity goes away.
The two are independent. An engine can exist with no Activity, for example a cached engine that runs before any screen is shown, or a background service. Your plugin can therefore be attached to the engine and still have no Activity. Any code that needs an Activity must handle that case.
The ActivityAware callbacks
ActivityAware has four methods.
| Callback | When it runs | What to do |
|---|---|---|
| `onAttachedToActivity(binding)` | The engine is attached to an Activity | Store the binding and register listeners |
| `onDetachedFromActivityForConfigChanges()` | The Activity is being destroyed for a configuration change, such as rotation | Release the Activity and unregister listeners. Keep other state. |
| `onReattachedToActivityForConfigChanges(binding)` | The new Activity is ready after the change | Store the new binding and register listeners again |
| `onDetachedFromActivity()` | The plugin is no longer attached to any Activity | Release everything that depends on an Activity |
The two "config change" callbacks exist so you can tell a rotation from a real departure. In both cases the old Activity object is gone and you must drop your reference to it. The difference is what else you keep. After a rotation, work that is still in progress usually continues on the new Activity. After a full detach, it usually cannot.
The ActivityPluginBinding
ActivityPluginBinding is the object you receive in the attach callbacks. It provides:
activity, the currentActivity.addActivityResultListenerandremoveActivityResultListener, for results ofstartActivityForResult.addRequestPermissionsResultListener, for runtime permission results.addOnNewIntentListener, for intents delivered to an already running Activity.
Flutter calls these listeners for you. This is why a plugin does not override onActivityResult itself. It cannot, because the Activity belongs to the app, not to the plugin.
Example: picking a document
The following method asks Android to show the system document picker and returns the chosen URI to Dart. It uses everything above: it needs an Activity, it waits for a result, and it must survive a rotation.
package com.example.battery_info
import android.app.Activity
import android.content.Intent
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
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
class BatteryInfoPlugin :
FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener {
private lateinit var channel: MethodChannel
private var activityBinding: ActivityPluginBinding? = null
private var pendingResult: Result? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "battery_info")
channel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"pickDocument" -> pickDocument(result)
else -> result.notImplemented()
}
}
private fun pickDocument(result: Result) {
val binding = activityBinding
if (binding == null) {
result.error("NO_ACTIVITY", "The plugin is not attached to an Activity.", null)
return
}
if (pendingResult != null) {
result.error("ALREADY_ACTIVE", "A document request is already in progress.", null)
return
}
pendingResult = result
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
}
binding.activity.startActivityForResult(intent, REQUEST_PICK_DOCUMENT)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode != REQUEST_PICK_DOCUMENT) return false
val result = pendingResult ?: return true
pendingResult = null
if (resultCode == Activity.RESULT_OK) {
result.success(data?.data?.toString())
} else {
result.success(null)
}
return true
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activityBinding = binding
binding.addActivityResultListener(this)
}
override fun onDetachedFromActivityForConfigChanges() {
detachFromActivity()
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
onAttachedToActivity(binding)
}
override fun onDetachedFromActivity() {
detachFromActivity()
pendingResult?.error("DETACHED", "The Activity went away before a result arrived.", null)
pendingResult = null
}
private fun detachFromActivity() {
activityBinding?.removeActivityResultListener(this)
activityBinding = null
}
private companion object {
const val REQUEST_PICK_DOCUMENT = 9001
}
}The Dart method is a thin wrapper. It returns null when the user cancels, which is not an error.
/// Opens the system document picker. Returns the content URI, or null if cancelled.
Future<String?> pickDocument() async {
try {
return await _channel.invokeMethod<String>('pickDocument');
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}Why the code is shaped this way
- The Activity is a nullable field.
activityBindingisnullwhenever there is no Activity. The method checks it first and reportsNO_ACTIVITYinstead of crashing. - The reference is cleared on every detach. Keeping the old Activity after a rotation leaks the whole destroyed screen.
- The listener is removed and added again. The binding lets Flutter keep a list of listeners. Leaving a stale one registered means a dead plugin state could receive results.
pendingResultsurvives a configuration change. OnlyonDetachedFromActivityfails it. If the user rotates the phone while the picker is open, the picker's result still reaches the sameResultobject and Dart gets its answer.- Only one request runs at a time. A single
pendingResultfield cannot hold two. The second call getsALREADY_ACTIVEinstead of overwriting the first and leaving it unanswered. - The request code is private to your plugin's choice.
onActivityResultreturnsfalsefor codes it does not own, so other plugins' listeners still get their turn. Pick a number unlikely to collide with other plugins.
Common errors
- Storing
binding.activitydirectly in a long-lived field and never clearing it. This leaks the Activity across rotations. - Assuming an Activity always exists. Use of
activityBinding!!crashes when the engine runs without a screen. Return an error code instead. - Registering listeners in
onAttachedToEngine. TheActivityPluginBindingdoes not exist yet. Register inonAttachedToActivity. - Forgetting to register again after a rotation. The new binding needs its own
addActivityResultListenercall. DelegatingonReattachedToActivityForConfigChangestoonAttachedToActivity, as above, avoids this. - Losing a pending request when the process is killed. Android can destroy the whole process while another app, such as the picker, is in front. Your plugin's fields are then gone. Keep such requests short and let Dart retry.
- Using the Activity as a
Contextfor long-lived work. Usebinding.applicationContextfrom the engine binding for anything that must outlive the Activity.
Testing the lifecycle
Dart unit tests with a mocked channel cannot reach this code. Test it on a device through the example app. Start the picker, rotate the device, then choose a file, and confirm that the Future completes with a URI. Repeat with the system "Don't keep activities" developer option enabled, which destroys each Activity as soon as you leave it, and confirm that nothing crashes.
Exercise
A user taps a button that calls pickDocument, and then rotates the phone while the picker is open. Which ActivityAware callbacks run, and what happens to pendingResult?
Show answer
onDetachedFromActivityForConfigChanges runs when the old Activity is destroyed, and onReattachedToActivityForConfigChanges runs when the new one is ready. The first clears activityBinding and removes the result listener. The second stores the new binding and adds the listener again. pendingResult is not touched, so when the user picks a file the new listener receives the result and answers the original Dart Future. Only onDetachedFromActivity fails the pending result with DETACHED.
Exercise
Why does pickDocument check activityBinding for null instead of using activityBinding!!?
Show answer
The engine can run without an Activity, for example a cached engine that has not been shown yet. In that state the binding is null, and !! would throw and crash the app. Returning a NO_ACTIVITY error lets Dart handle it as a PlatformException.