[Kotlin/Android] How do you prevent crashing your application when notifing to flutter through event channel?

Android

Problem

Don't you always come across a problem?!?! (<= Please don't say so : < )

I came across Android application crashing with flutter event channel (see event channel)

Some event channels worked correctly but one of that didn't work well and crash application.

And then, Logger showed me the following messages.

E/AndroidRuntime(31031): FATAL EXCEPTION: Thread-16
E/AndroidRuntime(31031): Process: com.smaho.mobile_app, PID: 31031
E/AndroidRuntime(31031): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: Thread-16
E/AndroidRuntime(31031):    at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:605)
E/AndroidRuntime(31031):    at io.flutter.embedding.engine.FlutterJNI.dispatchPlatformMessage(FlutterJNI.java:515)
E/AndroidRuntime(31031):    at io.flutter.embedding.engine.dart.DartMessenger.send(DartMessenger.java:76)
E/AndroidRuntime(31031):    at io.flutter.embedding.engine.dart.DartExecutor.send(DartExecutor.java:151)
E/AndroidRuntime(31031):    at io.flutter.view.FlutterNativeView.send(FlutterNativeView.java:144)
E/AndroidRuntime(31031):    at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler$EventSinkImplementation.success(EventChannel.java:226)

I coould find that this problem might happen in Android side.

In this case, these message were comparatively easy to understand and pointed out the problem directly.

E/AndroidRuntime(31031): java.lang.RuntimeException: Methods marked with @UiThread 

Solution

What you only have to fix is to execute eventSink on main(UI) thread.

// before
    fun notifyt() {
            eventSink?.success(
                mapOf(
                    KEY_EVENT_TYPE to "establishment",
                    "role" to role,
                )
            )
    }

//after
    //you must define `Handler` as main thread.
    pricate val uiThreadHandler = Handler(Looper.getMainLooper())

        fun notifyt() {
            uiThreadHandler.post{}
            eventSink?.success(
                mapOf(
                    KEY_EVENT_TYPE to "establishment",
                    "role" to role,
                )
            )
        }
    }

References

The following article really heps you guys to understarnd what thread is in Android.(Japanese)

コメント

タイトルとURLをコピーしました