Sub topic 6
Implementing the Android side in Kotlin
This chapter assumes you have already generated the battery_info plugin, declared its platforms in pubspec.yaml, and written the Dart BatteryInfo class that calls a MethodChannel named battery_info. You should be able to read basic Kotlin and know what an Android Context is. Here you write the native class that answers those calls.
Where the Android code lives
The generator creates the Android module under android/ in the plugin root. The Kotlin source sits at a path that mirrors the package name:
battery_info/
android/
build.gradle
src/main/
AndroidManifest.xml
kotlin/com/example/battery_info/BatteryInfoPlugin.ktThree names must agree, or the plugin will not load:
- The
packagevalue underflutter.plugin.platforms.androidinpubspec.yaml. - The
packagedeclaration at the top of the Kotlin file. - The
namespaceinandroid/build.gradle.
The pluginClass value must also match the Kotlin class name exactly. The Flutter tool uses these values to write the generated registrant in the app that depends on your plugin. A mismatch usually shows up as a build error in GeneratedPluginRegistrant.java, or as a MissingPluginException at runtime.
The FlutterPlugin contract
An Android plugin implements the FlutterPlugin interface. It has two required methods:
onAttachedToEngineruns when a Flutter engine starts using the plugin. Create the channel and register the handler here.onDetachedFromEngineruns when the engine goes away. Remove the handler here.
The class in this chapter also implements MethodCallHandler, which adds onMethodCall. That method receives every call that arrives on the channel.
package com.example.battery_info
import android.content.Context
import android.os.BatteryManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
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
class BatteryInfoPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
private lateinit var context: Context
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
channel = MethodChannel(binding.binaryMessenger, "battery_info")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"getBatteryLevel" -> {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) {
result.success(level)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
}
else -> result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}What each part does
The binding
FlutterPluginBinding is the object the engine hands to your plugin. Two of its members matter for most plugins:
| Member | Purpose |
|---|---|
| `binaryMessenger` | The pipe that carries channel messages. Pass it to `MethodChannel`. |
| `applicationContext` | A `Context` tied to the application, not to a screen. |
The application context is the right choice for system services such as BatteryManager. It does not leak an Activity, and it stays valid when the Activity is destroyed and recreated. It cannot show dialogs or start Activities for a result. Those jobs need an Activity, which is covered in a later chapter on the plugin lifecycle.
The channel name
The string "battery_info" must be identical on the Dart, Kotlin and Swift sides. It is compared exactly, including case. If the Kotlin side registers a different name, the Dart call never reaches your handler and fails with MissingPluginException. A common convention is to prefix the name with the package name, so two plugins do not collide.
The handler
onMethodCall receives a MethodCall and a Result. call.method is the string Dart passed to invokeMethod. call.arguments and call.argument<T>("key") give you the arguments.
For every call you must invoke exactly one of three Result methods:
success(value)returns a value, ornull.error(code, message, details)makes the DartFuturethrow aPlatformException.notImplemented()tells Dart the method name is unknown. Dart sees aMissingPluginException.
placeholderThe sequence below shows one successful call and one failing call.
Reading the battery safely
BatteryManager.getIntProperty(BATTERY_PROPERTY_CAPACITY) returns the charge as a percentage. If the device does not report the property, it returns Integer.MIN_VALUE. That is why the code tests level >= 0 before calling success. Sending a large negative number to Dart as if it were a real level would be a silent bug.
The error code "UNAVAILABLE" is the same string the iOS side uses. Keeping codes identical across platforms lets the Dart layer handle failures once, without a branch per platform.
Adding a method with different data
To show a second return type, add a method that reports whether the device is charging. The helper below reads the sticky battery broadcast. Passing null as the receiver returns the most recent value without registering anything.
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
fun isCharging(context: Context): Boolean {
val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
return status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL
}Put the function in the same package, then add a branch to the when in onMethodCall:
"isCharging" -> result.success(isCharging(context))Kotlin Boolean becomes a Dart bool with no extra work. The standard message codec maps these types:
| Kotlin or Java | Dart |
|---|---|
| `null` | `null` |
| `Boolean` | `bool` |
| `Int`, `Long` | `int` |
| `Double` | `double` |
| `String` | `String` |
| `ByteArray` | `Uint8List` |
| `List` | `List` |
| `Map` | `Map` |
A Float or a custom class is not supported. Convert it to a supported type before returning it. The channel then fails with an error that names the unsupported type.
Common mistakes
- Never calling
result. The DartFuturethen never completes and the calling code hangs. Every branch ofonMethodCallmust end in exactly one result call. - Calling
resulttwice. The engine logs an error and ignores the second call. This often happens when a callback and afinallyblock both reply. - Forgetting
else -> result.notImplemented(). Without it, a typo in a Dart method name hangs instead of failing quickly. - Skipping
setMethodCallHandler(null). The old handler keeps a reference to a dead engine. With multiple engines, this causes leaks and confusing behavior. - Throwing from
onMethodCall. An uncaught exception is turned into an error with the codeerror. Catch the exceptions you expect and report them with a specific code.
Checking your work
Run the example app on an Android device or emulator:
cd battery_info/example
flutter run -d androidIf the call returns a number, the wiring is correct. On an emulator the extended controls let you change the battery level, so you can watch the value change between calls. If you see MissingPluginException, confirm the three package names, the class name in pluginClass, and the channel string. After editing native code, stop the app and run it again. Hot reload and hot restart do not rebuild Kotlin.
Exercise
A Dart call to invokeMethod('getBatteryLevel') never completes, and no exception is thrown. The Kotlin handler contains a when block with a "getBatteryLevel" branch that calls manager.getIntProperty and then does nothing else when the level is negative. What is wrong, and what should the negative case do?
Show answer
The negative case never calls a Result method, so the Future stays pending forever. Every branch must call exactly one of success, error or notImplemented. The negative case should call result.error("UNAVAILABLE", "Battery level not available.", null), which makes Dart throw a PlatformException.
Exercise
You add an "isCharging" branch to the Kotlin when block, but Dart throws MissingPluginException when it calls invokeMethod<bool>('isCharging'). You use hot reload after the Kotlin edit. Give two likely causes.
Show answer
First, hot reload does not rebuild native code, so the running app still has the old Kotlin class and falls into the else branch, which calls notImplemented. Stop the app and run it again. Second, the method string may differ between Dart and Kotlin, such as "isCharging" versus "isCharge". The strings are compared exactly.