首页 > 解决方案 > Flutter Event Channel Stream 导致应用程序崩溃(与设备的连接丢失)

问题描述

我正在按照本文中描述的教程进行操作。
文章的代码可以在这里找到:https ://github.com/seamusv/event_channel_sample 。
我基本上做同样的事情,只是我使用 kotlin 而不是 java。

在本机代码 (MainActivity.kt) 中:

class MainActivity: FlutterActivity() {
  private val STREAM_TAG = "alarm.eventchannel.sample/stream";

  private var timerSubscription : Disposable? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    EventChannel(getFlutterView(), STREAM_TAG).setStreamHandler(
      object : EventChannel.StreamHandler {
        override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
          Log.w("TAG", "adding listener")
          this@MainActivity.timerSubscription = Observable.interval(0, 1, TimeUnit.SECONDS)
             .subscribe (
               {  
                 Log.w("Test", "Result we just received: $it");
                 events.success(1);
               }, // OnSuccess
               { error -> events.error("STREAM", "Error in processing observable", error); }, // OnError
               { println("Complete"); } // OnCompletion
             )
        }

        override fun onCancel(arguments: Any?) {
          Log.w("TAG", "adding listener")
          if (this@MainActivity.timerSubscription != null) {
            this@MainActivity.timerSubscription?.dispose()
            this@MainActivity.timerSubscription = null
          }
        }
      }
    )

  }
}

在我的 main.dart 中,我执行以下操作:

int _timer = 0;
  StreamSubscription _timerSubscription = null;

void _enableTimer() {
  if (_timerSubscription == null) {
    _timerSubscription = stream.receiveBroadcastStream().listen(_updateTimer);
  }
}

void _disableTimer() {
  if (_timerSubscription != null) {
    _timerSubscription.cancel();
    _timerSubscription = null;
  }
}

void _updateTimer(timer) {
  debugPrint("Timer $timer");
  setState(() => _timer = timer);
}

在构建函数中,我还创建了一个按钮,然后调用 _enableTimer() onPressed。

new FlatButton(
  child: const Text('Enable'),
  onPressed: _enableTimer,
)

每当我现在按下按钮调用 _enableTimer() 时,应用程序就会崩溃,并且我得到输出“与设备的连接丢失”......
我做错了什么还是这是 Flutter 新版本中的错误,因为这篇文章是从 12 月开始的2017 年?

标签: androidkotlinflutterdart

解决方案


我的问题的解决方案基本上是在主线程中启动流:

class MainActivity: FlutterActivity() {
  private val CHANNEL = "alarm.flutter.dev/audio"

  private val STREAM_TAG = "alarm.eventchannel.sample/stream";

  private var timerSubscription : Disposable? = null

  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine)

    EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), STREAM_TAG).setStreamHandler(
      object : EventChannel.StreamHandler {
        override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
          Log.w("TAG", "adding listener")
          this@MainActivity.timerSubscription = Observable
             .interval(1000, TimeUnit.MILLISECONDS)
             .observeOn(AndroidSchedulers.mainThread())
             .subscribe (
               {  
                 Log.w("Test", "Result we just received: $it"); 
                 events.success(it);
               }, // OnSuccess
               { error -> events.error("STREAM", "Error in processing observable", error); }, // OnError
               { println("Complete"); } // OnCompletion
             )
        }

        override fun onCancel(arguments: Any?) {
          Log.w("TAG", "adding listener")
          if (this@MainActivity.timerSubscription != null) {
            this@MainActivity.timerSubscription?.dispose()
            this@MainActivity.timerSubscription = null
          }
        }
      }
    )

  }

推荐阅读