Reputation: 366
I am implementing some native code to listen to volume up/down button press. The code it self to listen to this change works, but my problem is that once the EventChannel is created, the flutter app always receives data. I would like my app to listen to this changes only when is in the first screen, and when it navigates to the second screen it stops to listen to it, so that pressing the volume buttons behaves in the normal way.
On my Flutter class, I have created the EventChannel
like this
class _MyAppState extends State<MyApp> {
final eventChannel = EventChannel("event_channel");
@override
void initState() {
super.initState();
eventChannel.receiveBroadcastStream().listen((event) {
print(event);
});
}
on the MainActivity for native android I wrote this
lateinit var eventChannel: EventChannel
var eventSink: EventChannel.EventSink? = null
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
...
eventChannel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL)
eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events!!
}
override fun onCancel(arguments: Any?) {
eventSink = null
}
})
}
private val handler = Handler(Looper.getMainLooper())
private var skip = false
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val keyCode = event.keyCode
if (eventSink != null &&
!skip &&
(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
eventSink?.success(keyCode)
skip = true
// dispatchKeyEvent is called twice
handler.postDelayed({
skip = false
}, 100)
return true
}
return super.dispatchKeyEvent(event)
}
Upvotes: 0
Views: 563
Reputation: 9257
When you start listening to a Dart Stream with listen()
you get back a StreamSubcription
object. When you want to stop listening, you have to call the cancel()
method of the subscription.
So if you want only to listen while your page is visible you have to subscribe to it when navigating to the page/popping any page above and cancel the subscription when you navigate away from this page. Depending on how you do your navigation probably a good place to do that would be a NavigationObserver. You can find an introduction on Streams in my blog post https://www.burkharts.net/apps/blog/fundamentals-of-dart-streams/
Upvotes: 0