Skip to content Skip to sidebar Skip to footer

Scan And Listen To Events From Bluetooth Devices In Background With Flutter

I want to set up a mobile application with flutter which also runs in the background. this application allows you to scan Bluetooth devices and listen to events to launch notificat

Solution 1:

There are 2 ways to do it.

  1. All you have to do that is write a native code in JAVA/Kotlin for android and obc-c/swift for ios.

The best place to start with this is here

If you just follow the above link then you will be able to code MethodChannel and EventChannel, which will be useful to communicate between flutter and native code. So, If you are good at the native side then it won't be big deal for you.

// For example,  if you want to start service in android // we write//rest of the activity codeonCreate(){
  startBluetoothService(); 
}


startBluetoothService(){
//your code
}
//then, For the flutter// Flutter side MessageChannel msgChannel=MessageChannel("MyChannel");
msgChannel.invokeMethode("startBluetoothService");

// Native sidepublicclassMainActivityextendsFlutterActivity {
  privatestatic final StringCHANNEL = "MyChannel";

  @OverridepublicvoidconfigureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
  super.configureFlutterEngine(flutterEngine);
    newMethodChannel(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 executionif (result != -1) {
                result.success(batteryLevel);
              } else {
                result.error("UNAVAILABLE", "Battery level not available.", null);
              }
            } else {
              result.notImplemented();
            }
          }
        );
  }
}


same as above you can write the code for the iOS side.

  1. Second way is to write your own plugin for that you can take inspiration from alarm_manager or Background_location plugins.

I hope it helps you to solve the problem.

Post a Comment for "Scan And Listen To Events From Bluetooth Devices In Background With Flutter"