khoutech
khoutech

Reputation: 11

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 notification and/or start a ringtone. I managed to do all this and it works very well with the flutter_blue plugin. But my problem is that the application has to keep running in the background.

I came here to seek help.

The app does exactly what this app does https://play.google.com/store/apps/details?id=com.antilost.app3&hl=fr&gl=US

Upvotes: 1

Views: 4621

Answers (1)

Code Runner
Code Runner

Reputation: 1028

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 response = startBluetoothService();

//then you can return the result based on the your code execution
              if (response != -1) {
                result.success(response);
              } else {
                result.error("UNAVAILABLE", "Error while starting service.", 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.

Upvotes: 2

Related Questions