Demo Android Application

The demo app for this project is a default Flutter app created with flutter create along with some basic UX and custom native code for handling the bluetooth connection itself. The reason for the custom native code is because I had forgotten to power on my test board prior to attempting to pair it using a community package, and it wasn’t working. I assumed the package had issues, so I made one right quick before realizing what happened. C’ést la vie. 😆

Let’s take a look at the application entry point file, lib/main.dart:

The file lib/main.dart contains the application UX, which consists of a title bar, the sensor readout, and the power button for turning on and off the LED on the board. In this file we have some imports for dart:async along with the bt-controller.dart file, the client side implementation of the native bridge.

When the application starts, the BTController class is initialized and then a list of available devices is requested from it, which is in turn displayed to the user with a non-dismissable dialog box. When a device is selected, the controller is instructed to connect to it, at which point it will begin forwarding data read from the device to the handler passed into the initialization method.

As the MainPage class receives data from BTController, it will store the data in sensorValue using a setState() command which triggers a screen refresh. When the FloatingActionButton is pressed, a single alternating character of either a ‘0’ or a ‘1’ is sent to BTController for transmission to the module.

Next up we’ll take a look at the file lib/bt-controller.dart:

The BTController class employs a MethodChannel to enable communication between the Flutter UX code in Dart and the native Android code for low-level bluetooth logic. The init(Function onData) method initializes the method call handler and redirects calls to it to the onData function to pass messages back upstream to the view logic. Methods have been defined to encapsulate and forward requests to the platform native code for convenience and readability.

We won’t go into detail about the platform-specific code for implementing the bluetooth logic itself since that is outside of the scope of this article, as this would often be handled by using a pre-made plugin such as flutter_blue or flutter_bluetooth_serial. If you’re interested and you would like to check it out, the MainActivity.java file can be found here, or you can choose to clone the whole project from here and take a look or experiment with it. That wraps up the logic portion of this project, so now it’s time to check out how it works.