Sub topic 8
Streaming events from Android
This chapter covers the Kotlin half of an EventChannel. You already know the Dart side, where receiveBroadcastStream() returns a Stream. Here you write the native object that feeds that stream and make sure it starts and stops cleanly.
What you need first
This chapter assumes you have read the chapter on the Dart side of EventChannel. It also assumes you can read simple Kotlin, know where MainActivity lives in android/app/src/main, and understand Stream.listen and StreamSubscription.cancel.
The contract: EventChannel.StreamHandler
On Android, an EventChannel is a name plus a StreamHandler. The handler is an interface with two methods:
onListen(arguments: Any?, events: EventChannel.EventSink)runs when Dart starts listening.argumentsis whatever Dart passed toreceiveBroadcastStream.eventsis the object you use to send data back.onCancel(arguments: Any?)runs when Dart stops listening. You stop producing events and release resources here.
Dart's receiveBroadcastStream() returns a broadcast stream. The first Dart listener triggers one onListen, and the cancellation of the last Dart listener triggers one onCancel. Extra Dart listeners share the same native stream. If the native side receives a second onListen while one is active, the engine calls onCancel on the old subscription first. Your handler therefore holds at most one live sink, but it must still tolerate this sequence.
A complete handler
This handler sends an incrementing integer every second. It is the Kotlin half of the TickService example.
import android.os.Handler
import android.os.Looper
import io.flutter.plugin.common.EventChannel
class TickStreamHandler : EventChannel.StreamHandler {
private val handler = Handler(Looper.getMainLooper())
private var sink: EventChannel.EventSink? = null
private var count = 0
private val ticker = object : Runnable {
override fun run() {
sink?.success(count++)
handler.postDelayed(this, 1000)
}
}
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
sink = events
count = 0
handler.post(ticker)
}
override fun onCancel(arguments: Any?) {
handler.removeCallbacks(ticker)
sink = null
}
}Three details matter here.
- The sink is stored in a field.
onListenreturns immediately, but events keep flowing later, so you must keep the sink. onCancelstops the source before it clears the sink. If you cleared only the sink, theRunnablewould keep rescheduling itself forever. Usingsink?.successwould hide that bug, because nothing visible would fail.- The
HandlerusesLooper.getMainLooper(). This keeps everysuccesscall on the main thread, which the threading section below explains.
Registering the handler
Create the channel in configureFlutterEngine, using the same name string as Dart. Keep a reference to the handler so you can clean up when the engine goes away.
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
class MainActivity : FlutterActivity() {
private val ticksChannelName = "com.example.app/ticks"
private var tickHandler: TickStreamHandler? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val handler = TickStreamHandler()
tickHandler = handler
EventChannel(flutterEngine.dartExecutor.binaryMessenger, ticksChannelName)
.setStreamHandler(handler)
}
override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
tickHandler?.onCancel(null)
tickHandler = null
super.cleanUpFlutterEngine(flutterEngine)
}
}The cleanUpFlutterEngine override handles the case where the activity is torn down while Dart is still subscribed. In that case the engine may never deliver an onCancel. Calling it yourself is safe because the handler's onCancel can run more than once without harm.
On the Dart side, listen and cancel as follows. The onError callback receives errors that native code sends with events.error.
import 'dart:async';
import 'package:flutter/services.dart';
class TickService {
static const EventChannel _events = EventChannel('com.example.app/ticks');
Stream<int> get ticks =>
_events.receiveBroadcastStream().map((event) => event as int);
}
Future<void> demo() async {
final sub = TickService().ticks.listen(
(value) => print('tick $value'),
onError: (Object error) {
if (error is PlatformException) {
print('native error: ${error.code} ${error.message}');
}
},
onDone: () => print('native side closed the stream'),
);
await Future<void>.delayed(const Duration(seconds: 5));
await sub.cancel(); // triggers onCancel in Kotlin
}The three EventSink methods
| Method | What Dart sees | Notes |
|---|---|---|
| `success(value)` | A data event | `value` must be a type the standard codec supports. `null` is allowed. |
| `error(code, message, details)` | An error event, as a `PlatformException` | The stream stays open. Later events still arrive. |
| `endOfStream()` | The `onDone` callback | The stream closes. Call nothing on the sink afterward. |
An error event does not end the stream. If a sensor glitches once, send error and keep sending data. Call endOfStream only when the source is finished, for example when a file has been read to its end. A continuous source such as a tick timer never needs it.
A realistic source: a BroadcastReceiver
Timers are good for learning, but most Android event sources are callbacks that you register and unregister. The pattern is the same. Register in onListen and unregister in onCancel. This handler streams the battery percentage whenever the system reports a change.
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import io.flutter.plugin.common.EventChannel
class BatteryStreamHandler(private val context: Context) : EventChannel.StreamHandler {
private var receiver: BroadcastReceiver? = null
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
val newReceiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
if (level < 0 || scale <= 0) {
events.error("UNAVAILABLE", "Battery level not available.", null)
} else {
events.success(level * 100 / scale)
}
}
}
receiver = newReceiver
context.registerReceiver(newReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}
override fun onCancel(arguments: Any?) {
receiver?.let { context.unregisterReceiver(it) }
receiver = null
}
}Register it in configureFlutterEngine with BatteryStreamHandler(applicationContext). A receiver registered with a Context runs on the main thread by default, so events.success is called from the right thread without extra work. ACTION_BATTERY_CHANGED is a sticky broadcast. Android delivers the current state shortly after registration, so the Dart listener gets a first value without waiting for a change.
Threading rules
Send every event from the platform thread, which on Android is the main thread. Callbacks from other threads, such as a network library or a HandlerThread, need to be moved to the main thread first:
private val mainHandler = Handler(Looper.getMainLooper())
fun deliver(value: Int) {
mainHandler.post { sink?.success(value) }
}Reading sink inside the posted block, rather than capturing it earlier, matters. By the time the block runs, Dart may have cancelled and onCancel may have cleared the field. The ?. then turns the call into a no-op instead of a use of a dead sink.
Do not do slow work inside onListen or onCancel. They run on the main thread, and blocking there freezes the UI. Start the work on a background executor and post results back.
Common errors
MissingPluginExceptionwhen listening. The channel name differs between Dart and Kotlin, or the handler was never registered. Compare the strings character by character. Also check that a hot restart did not leave you running an older native build, since native code needs a full rebuild.- Events keep firing after
cancel().onCanceldid not stop the source. Check that you unregister listeners and remove posted callbacks, not only clear the sink. - Crash or dropped events when sending.
successwas called from a background thread. Post to the main looper first. - Listening twice and getting a duplicate source. Your
onListencreated a new timer or receiver without stopping the old one. Stop any existing source at the top ofonListen, or rely on the engine callingonCancelfirst and test that path. - State left over from a previous subscription. Reset fields such as
countinonListen, asTickStreamHandlerdoes.
Exercises
Exercise
Your Kotlin handler posts a Runnable every second with Handler.postDelayed. In onCancel you set sink = null but forget handler.removeCallbacks(ticker). The Runnable calls sink?.success(...). What goes wrong, and why does nothing crash?
Show answer
The Runnable keeps rescheduling itself forever, so the timer leaks and keeps waking the main thread after Dart has cancelled. Nothing crashes because sink?.success is a no-op when sink is null. The fix is to call handler.removeCallbacks(ticker) in onCancel before clearing the sink.
Exercise
A third-party location library calls your Kotlin callback on its own worker thread. How do you deliver each location to Dart safely?
Show answer
Post the call to the main looper, for example Handler(Looper.getMainLooper()).post { sink?.success(value) }. Read the sink field inside the posted block, so a cancel that happened in the meantime leaves it null and the call is skipped.