Flutter本机代码-在单独的隔离中调用平台通道

时间:2019-09-05 04:41:35

标签: android flutter

我试图将本机代码添加到我的flutter应用程序中,该应用程序基本上只有2种播放和停止警报的方法。我在MainActivity和dart中在android中添加了本机代码,但出现异常: 未处理的异常:MissingPluginException(在com.example.smart_alarm / android_ring_manager通道上未找到方法playAlarm的实现)

已经尝试:

(i)。卸载/重新安装应用程序

(ii)。颤动干净,颤动运行

(iii)。更改频道名称

'''

private static final String CHANNEL_NAME = "com.example.smart_alarm/android_ring_manager";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

    startService(new Intent(this, AlarmRingerService.class));

    new MethodChannel(getFlutterView(), CHANNEL_NAME).setMethodCallHandler((call, result) -> {
        if (call.method.equals("playAlarm")) {
            System.out.println("MainActivity: Playing alarm");
            AlarmRingerService.playAlarm();
            result.success(null);
        } else if (call.method.equals("stopAlarm")) {
            System.out.println("MainActivity: Stopping alarm");
            AlarmRingerService.stopAlarm();
            result.success(null);
        }
    });
}
Flutter dart code: This is executed from alarm callback in separate isolate

import 'package:flutter/services.dart';

class AlarmRingManager {
  static const MethodChannel _channel =
      const MethodChannel('com.example.smart_alarm/android_ring_manager');

  static Future<void> playAlarm() async {
    try {
      await _channel.invokeMethod('playAlarm');
    } on PlatformException catch (e) {
      print('Unable to call play alarm on platform channel $e');
    }
  }

  static Future<void> stopAlarm() async {
    try {
      await _channel.invokeMethod('stopAlarm');
    } on PlatformException catch (e) {
      print('Unable to call stop alarm on platform channel $e');
    }
  }
}

我在这里错过了什么吗?我是否需要在其他地方或清单中注册我的方法调用处理程序?

-----------编辑----------------------------------- -------------

因此,我对其进行了更多调试,并发现问题不在于平台通道回调。问题是我从android_alarm_manager回调中调用平台通道方法。由于android_alarm_manager在不同的隔离中运行,并且在主隔离中设置了方法调用处理程序,因此无法找到它。

有没有一种方法可以在android BE服务中定义平台通道,以便它始终可用于所有隔离?如果将其用于现有插件,我可以看到它正常工作,但是我不确定如何添加自己的代码,以便本机平台通道可用于所有隔离。

0 个答案:

没有答案