Home > Software engineering >  How to know if my App is connected to a device using BLE in Flutter?.. when app is the beacon
How to know if my App is connected to a device using BLE in Flutter?.. when app is the beacon

Time:03-10

So my android app is behaving as a beacon, means, it will be advertising and other BLE devices will be connecting to it. Well, this is how our project is working so please don't raise questions on this as why am i using my app as a beacon and not as a scanner. Anyways, It behaves as a beacon and starts advertising and now I want to know that if a device connected to it. I cant find a way how to do this.

Of course, I am using this flutter package. beacon_broadcast 0.3.0

This is my code.

  void startAdvertising() {
    BeaconBroadcast beaconBroadcast = BeaconBroadcast();
    beaconBroadcast
        .setUUID(advertisingUUID)
        .setMajorId(1)
        .setMinorId(100)
        .start();
  }

CodePudding user response:

First, Flutter is just a UI toolkit and has no support for other system APIs such as Bluetooth.

You should therefore look what the official Android APIs offer in the first place. Usually when using BluetoothLeAdvertiser for advertising, one often also adds an instance of BluetoothGattServer in order to handle connections. If you have created a BluetoothGattServer using openGattServer, you will get a onConnectionStateChange callback whenever a device connects or disconnects. So that answers your question how an Android app can get notified when a device connects. You probably also want to use the same API to add a GATT service so that the other device can communicate with your app. Other alternatives is to use the GATT client API if it's the other device that has a GATT server, or you might want to use the L2CAP CoC API.

Note that if Bluetooth is turned off/disabled/restarted, your BluetoothGattServer object will automatically die and you need to recreate it. To get notified when this happens, use a state change intent receiver for BluetoothAdapter.ACTION_STATE_CHANGED as explained in this example https://stackoverflow.com/a/9694138/556495 to recreate your BluetoothGattServer (and advertiser) when state is changed to STATE_ON.

Now, since you want to use Flutter but Flutter uses Dart, you cannot directly consume the Android APIs. Instead you need to write a bridge/plugin, to bridge your Dart code and Java code. See https://docs.flutter.dev/development/platform-integration/platform-channels for a tutorial how to do this. If you're lucky, someone else might have already created such a package that does exactly what you want. Unfortunately, the beacon_broadcast package you found, only implements BluetoothLeAdvertiser and not BluetoothGattServer, as can be seen by the source code here: https://github.com/pszklarska/beacon_broadcast/tree/master/android/src/main/kotlin/pl/pszklarska/beaconbroadcast.

  • Related