【问题标题】:Scan and listen to events from Bluetooth devices in background with flutter使用颤振在后台扫描和收听来自蓝牙设备的事件
【发布时间】:2020-11-11 11:48:15
【问题描述】:

我想用颤振设置一个移动应用程序,它也在后台运行。此应用程序允许您扫描蓝牙设备并收听事件以启动通知和/或启动铃声。 我设法做到了这一切,它与 flutter_blue 插件配合得很好。但我的问题是应用程序必须在后台继续运行。

我是来寻求帮助的。

该应用完全符合该应用的功能https://play.google.com/store/apps/details?id=com.antilost.app3&hl=fr&gl=US

【问题讨论】:

    标签: android ios flutter background-process foreground-service


    【解决方案1】:

    有两种方法。

    1. 您所要做的就是在 JAVA/Kotlin 中为 android 编写本机代码,为 ios 编写 obc-c/swift 代码。

    最好的起点是here

    如果您只是按照上面的链接,那么您将能够编写 MethodChannel 和 EventChannel,这将有助于在 Flutter 和原生代码之间进行通信。所以,如果你擅长原生方面,那对你来说没什么大不了的。

    // For example,  if you want to start service in android 
    
    // we write
    //rest of the activity code
    onCreate(){
      startBluetoothService(); 
    }
    
    
    startBluetoothService(){
    //your code
    }
    //then, For the flutter
    
    // Flutter side 
    
    MessageChannel msgChannel=MessageChannel("MyChannel");
    msgChannel.invokeMethode("startBluetoothService");
    
    // Native side
    
    public class MainActivity extends FlutterActivity {
      private static final String CHANNEL = "MyChannel";
    
      @Override
      public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
      super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
            .setMethodCallHandler(
              (call, result) -> {
               if (call.method.equals("startBluetoothService")) {
                  int result = startBluetoothService();
    
    //then you can return the result based on the your code execution
                  if (result != -1) {
                    result.success(batteryLevel);
                  } else {
                    result.error("UNAVAILABLE", "Battery level not available.", null);
                  }
                } else {
                  result.notImplemented();
                }
              }
            );
      }
    }
    
    
    

    同上你可以写iOS端的代码。

    1. 第二种方法是编写自己的插件,您可以从 alarm_managerBackground_location 插件中获取灵感。

    希望能帮到你解决问题。

    【讨论】:

    • 感谢您的回答,非常有用。我知道如何将颤振代码与我制作了很多这样的应用程序的本机代码进行通信。但是,我想要的是扫描也可以在后台运行。因此,如果我理解您的意思,我必须在 android 端创建一个前台服务才能拥有通知栏。但问题是,我不知道应该在哪里编写后台扫描的代码,也不知道如何在后台保持与蓝牙设备的连接。谢谢。
    • 意味着您可以将代码写入您的本地蓝牙前台服务,您可以在其中触发您的启动和停止方法。我没有用蓝牙制作,但我用位置制作了它,它工作正常,因为当时没有开发后台定位服务插件。因此,要启动和停止,您可以使用方法 Channel 并流式传输扫描结果,您可以使用事件通道(对我来说,我正在发送新位置)。您可以在事件通道流的 onListen/onData 方法中处理这些数据。希望对您有所帮助。
    • 谢谢,但我不太明白你的意思。我不是安卓专家,有些东西我还是不明白。你能给我一些示例代码,以便我明白你的意思吗?这样我会更好理解。再次感谢。
    • 如果我的解释有点混乱,我很抱歉,但您肯定可以查看此链接,该链接将引导您进入演示:gestyy.com/erHe9h。谢谢 希望这能帮助您更好地理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2020-06-03
    相关资源
    最近更新 更多