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 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();
            }
          }
        );
  }
}


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"