Android app architecture with BLE - android

I am developing an android app with BLE API from android. My app needs to connect to a BLE device, and remain connected as long as it is in range and turned on. I need to read data from it, and write data to it.
I am trying to follow the MVP architecture pattern, not strictly since activities are the starting point. But anyway, I wanted to know where should I put the interaction with Bluetooth? I am searching for answers for the following questions. I have searched StackOverflow, but couldn't find what I was looking for.
Should it be in a service bounded to the UI just like in googlesample ble app ? But, I think that would break the whole mvp architecture.
Should it be a bounded service at all ? If no, what would be the best way to implement the service? In my mind, if it's not bounded to the view, and there is a callback from the background service to display something on the UI, there is a possibility of undefined behavior.
Who should initiate the Bluetooth interaction ? The application class or some activity ?
I am looking for mainly architectural guidance, and best way to go about developing this app.

Since you have the requirement that the Bluetooth connection should keep working in the background, you should have a Foreground Service somewhere running in your app process. This will make sure your app process will be kept alive, but requires an icon to be displayed in the phone/tablet's top bar.
Whether you actually put your BLE code in this service class or not doesn't matter for the functionality.
There are of course many ways to achieve good architecture but here is my approach.
My approach would be to have a singleton class that handles all your BLE scanning, connections and GATT interactions (from now on called Manager). Since some BLE operations needs an Android Context, a good way is to use the Application context as context. Either follow Static way to get 'Context' on Android? to be able to fetch that context at any time or subclass the Application class and from its onCreate call some initialization method in your Manager and pass the context. Now you can keep all BLE functionality completely separated from Android Service/Activity/Application stuff. I don't really see the point in using bounded services etc. as long as you keep everything in the same process.
To implement a scan functionality, you can have a method in your Manager that creates Scanner objects. Write the Scanner class as a wrapper to Android's BLE scanner and expose methods to start/stop scan. When you create a Scanner that method should also take an interface as argument used for callbacks (device reports and errors). This class can now be used in for example an Activity. Just make sure that the scanner gets stopped in the Activity's onStop method to avoid leakage of objects.
There are several reasons for having a wrapped custom Scanner object instead of using Android's BLE scan API directly in the Activity. First you can apply the appropriate filtering and processing of advertising packets so it handles your type of peripheral and can show high level parameters (decoded from advertising data) in your custom advertising report callback. The manager should also listen to broadcasts when Bluetooth gets started/stopped/restarted and keep track of all started Scanners so the Scanners are restarted seamlessly when Bluetooth restarts (if you want this functionality). You may also want to keep track of timestamps of all scan starts/stops so you can workaround the new restrictions in Nougat that limits it to 5 scans per 30 seconds.
Use a similar approach when you want to connect to your peripherals. You can for example let the Manager create Device objects which have methods to start/stop the connection and have a callback interface to report events. For each supported feature (for example read some remote value) you should expose a method which starts the requests and have a callback which is called when the result arrives. Then your Manager and Device class takes care of the GATT stuff (including enqueuing all your GATT requests so you only have one outstanding GATT operation at a time). Just make sure you can always abort or ignore the result when you don't want the result, for example if an Activity's onStop or onDestroy method is called.
Since you probably want to reconnect automatically in case the device gets disconnected, you should use the autoConnect flag and set it to true when establishing the connection, which assures this. Again, the Manager should keep track of all active Device objects and automatically recreate the BluetoothGatt object when Bluetooth is restarted.
To be able to display different kind of UI stuff, like for example automatically show a warning message in your Activity when Bluetooth is turned off and remove it when Bluetooth is turned on, you should be able to register Listeners to your Manager. Have a method in your Manager for registering/unregistering a listener (which is really just a Callback) object, keep track of all the listeners and when Bluetooth state change happens, call all listeners. Then in your Activity's onStart you register a listener and in onStop you unregister it. You can have a similar approach for your Device's BLE notifications, where applicable.
What's left is how you deal with different Threads. As you might know most BLE callbacks from Android's API happen on Binder threads, so you may not update the UI from them. If you otherwise in your app don't use anything other than the main thread, you can for example post all invocations of callbacks in the Manager to the main thread, or maybe move to the main thread directly when the callback from Android's BLE stack arrives (but then be aware of things like https://bugs.chromium.org/p/chromium/issues/detail?id=647673). Just make sure you never touch the same variables from different threads.
Also if you target API 23 or higher you need UI code to let the user give permission to Location to be able to start scan. I suggest you implement this in your UI code and not in the Manager, or implement some "wrapper" or helper method in the Manager to do this.

RxCentralBle provides a paradigm for use in an app. The library design clearly shows the structure of the library. In short, RxCentralBle provides reactive interfaces for the primary Bluetooth LE actions:
BluetoothDetector - detect phone Bluetooth State
Scanner - scan for peripherals
ConnectionManager - connect to a peripheral
PeripheralManager - queue operations to communicate with a peripheral
It's recommended to subscribe to these interfaces on a background thread and ensure resources and subscriptions live at the application scope i.e. member variables of your Application class. As long as your Application is running, all Bluetooth LE resources will remain alive and active.
Check out RxCentralBle's Wiki and sample app to learn more.

Related

Is it a good idea to use Service as Presenter in MVP context

Short stated my question is: in MVP architecture is it a good idea to use a Service as
Presenter to control a Model implemented as Service ?
Alternative question: Is using a Service to control another Service a good idea ?
The context:
I am writing an app that communicates with a bluetooth sensor.
The app has a Service
(aka BluetoothService) that makes the connection and manages the communication with the sensor.
The app has several Fragments but just few of them are related to the operations that
the Bluetooth sensor does. A user should be able to start an operation, navigates to different
fragments and later watches the results of the operation(s) done by the sensor.
My purpose:
I want to write a component (aka BluetoothController) that makes the links
between the sensor (represented in my app by BluetoothService) and the rest of
the app. The BluetoothController contains Objects that described what kind of
operation has to be done by the sensor (only one operation, serial operations,
type of the operation, ...), so BluetoothController 's purpose is to let
the operations be independant to Bluetooth sensor and then be able to test the app
with a mock bluetooth class. I see BluetoothService as a model and
BluetoothController as a presenter, am I wrong ?
Why a Service:
Because it does not die if the user navigates between fragments
Because it is accessible through the whole app via bindService
Because bindService is the only entry point, I guess I can control that just
one operation is done at a time
Because I see Service as an active component, so it can keep on receiving data even if there is nothing bound to it
This service would be both started and bind (like a music player):
to be able to keep on running even if no components are bound to it,
to ease communication
All services would be in the application process to let communication be done
without binder but rather
method call.
Any suggestion would be highly appreciate , thanks in advance
Why not something else:
RetainedFragment are (for me) just container
pojo presenter are just gateway between views and models, they should die if
they are not attached to a view.
Conclusion
Am I wrong? Do you see difficulties in this architecture? Are there other Android
components that suits my purpose better?
Any suggestions would be highly appreciated, thank you in advances

Accessing a Bluetooth "ConnectedThread" from various activities

I have created a BluetoothManager much like the one in this example. This object is instantiated in a connection activity, reached from the main acitivty by clicking on a "Connect" button, which provides a ListView of selectable devices. Works great so far.
I am now connected and have a BluetoothManager.ConnectedThread running and the streams set up. I would now like to be able to send Bluetooth data from/to various other activities when they are running. For example, I will want to chart realtime values when the charting activity is running.
As far as I can tell, the pushing of the data out from the ConnectedThread will occur via a Handler, which is a new topic for me. What I am unclear on his how other activities might access the ConnectedThread's write() function.
First of all, even though a singleton could be a solution, android Service's are there for this purpose, since these are elements that can keep running when your UI is out. So my suggestion would be to create a sticky service an then you have two options:
Handle data using a handler between the activity and the Service. Maybe if you are not too familiar with the Handler api this will take some time to you. In this example of the official documentation you can also check how to use the handler.
Create a bound service, to which you can bind from the activities and send some data when required. Here you have the official information about bound services.
You can have a look to this tutorial to get more information about handlers.

Strategy to handle Nearby Messages API - Android

I am currently working on an messaging application for Android that communicates with other devices using Nearby Messages API. Since this is the first time that I work with this API, I would like to know if there is a pattern or strategy to handle the connections.
For instance, when the user changes the activity (e.g. opens a new conversation), I would like to keep the connection active, so I would like to work with a Connection Manager or something to keep listening and parsing the messages.
We kept working on our code, and finally we decided to implement a ConnectionManager as a single instance. This way all the activities in the application are able to access to the same methods. We also avoid to have several instances of GoogleApiClient, and then know if we are connected or not (e.g. isConnected() method).
However, we also needed in some methods the context or the activity, but we solved passing these parameters as arguments in those methods.
To sum up:
Singleton pattern: avoid creating several instances of the same GoogleApiClient
Proxy pattern: encapsulate GoogleApiClient methods in a class that handles the whole connection, instead of delegating this task on activities

Application vs Service vs Intent

I am creating a project which connects to an embedded Bluetooth chip. Currently I have it set up with a separate application class which controls all the bluetooth functionality.
My program initialized with a main menu that has 9 buttons. In the main screen I create the connection to the Bluetooth device. Each button brings me to a separate Activity. Each activity needs to receive different pieces of data from the Bluetooth chip.
My question to you all is, would it make sense for me to use a service instead of an application? From what I understand of a service, it is used because there is always something running in the background. However in this case nothing needs to be running in the background ( unless keeping the connection with the Bluetooth device counts), data is only sent/received when an Activity asks for it.
Or, am I completely off track and shouldn't use either? Just a simple class to act as my data container which can be passed through intents? I know this will work, but am very new to Android and intents seem to be a bit messy. I would rather not use intents if I didn't have to.
I'm also building up a bluetooth connection, and i put the whole communication stuff in a service and bind to this service with every activity that needs to use the connection. This works pretty well for me. You might want to choose this way too.
Actually i earlier realised a way holding the connection in the application, but now i prefer the service way, because i'm using the application for global states.
Using service also reduces the need of intents to a very small amount :)
In your case a static property for the bluetooth connection would be the most pragmatic solution

Am I using and Android in-memory way to share data that's simply not the way the Android activity model works?

I've asked various questions related to one goal: how to develop an Android app that plots bluetooth data forever in real-time. I now have a new question from a different angle. To be fair to new readers I will cover some of the same background, but basically the question is in the title.
I found some open source code Bluetooth that apparently creates a background thread which updates the screen with new data it receives over a bluetooth connection. Then when I launch my Plot activity I can see the bluetooth background thread continue to write bluetooth data to Logcat. So I know for a fact the bluetooth background thread is still running when I launch my Plot activity.
Again, my goal is to plot the bluetooth data that is continually provided by the bluetooth background thread. I have succeeded as follows: since this bluetooth background thread seems to run continually and just won't die, I decided to use its update() method to call my static Plot.plotData() method to plot the data. And this works. It will will run endlessly with out a problem - receiving bluetooth data and plotting it via periodic calls from the bluetooth background method update() to my static Plot.plotData() method.
Although I have received some negative feedback regarding my solution, I have found sharing data across Activities where Edward Falk says sharing static data is OK. Here Edward Falk asks: "Are the activities all in the same application? [yes] Same task? [not sure] It seems to me that you could just store the data in a static variable accessible by all of the activities." Well I tried static data and it worked, but I switched to a static method Plot.plotData() which seems to work better for me.
The latest feedback I have received from one person #emmby that says my static Plot.plotData() goes against the following: "It sounds like you're looking for an in-memory way to share data, and that's simply not the way the Android activity model works." But what am I else to do? I thought that an Android phone has a limited amount of RAM for running Activities (one at a time), threads, handlers, Services, AnycTasks, etc. And an SD card for persisting data.
#emmby seem to say that in order to share data from a bluetooth background thread to my Plot activity (Plot.plotData()) that I must use the SD card. This doesn't sound right. After all I have it working using my static method Plot.plotData().
Frankly I don't see anything wrong with my solution primary because those who criticize it do not follow up with a definitive alternative.
If you find my solution deficient please speak up and provide a definitive solution. Otherwise I will take Edward Faulk's solution as the best one.
If I understood you correctly, your thread is running at the background even when none of the activities display data obtained by that thread. For example, let's consider scenario:
You started your bluetooth thread.
Your activity A started and now read data from that thread.
Your activity A is backgrounded (for example user navigates away via "Recent" tasks).
Your activity is idle but bluetooth thread still consumes cpu and power.
If you don't use your bluetooth data you shouldn't run the thread. You can introduce some kind of counter that tracks number of clients that use your thread's data. And if counter drops to zero - thread stops/pauses.
But Android has built-in solution for such cases. You can introduce service which will be bound by different activities and will have DataSource interface with getNextData function. See Bounded Services for more details.
When there are no clients bound to service Android will stop the service. This way you completely decouple Activities from thread. Your bluetooth thread is now managed by Service. And Service is now managed by Android.
In your case Local Service should be enough to share data between your thread and activities.

Categories

Resources