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
Related
I have many Activities that have several fragments. Part of the work those fragments do is to make authenticated network calls. It is possible that the token will expire. When that happens, I will see the 401 in the networking layer. What is the preferred method to communicate back to up the stack to whichever fragment initiated the network activity that it needs to initiate the logoff procedure? In other words, when the networking layer gets a 401, I want to communicate that back to the UI that the user needs to be log offeven though many other Activities may have also been invoked since then. This is often done via custom exceptions being handled in the app but I was wondering if there was a specific pattern that was preferred other than that. Something using Live Data perhaps?
You should separate in layers. Each layer should be responsible of a single task. There are many ways to do this, but you could use the MVVM Google approach which consists in:
M (Model): data classes and repositories that persist/retrieve them.
V (View): Activities/Fragments that observe data objects (LiveData) exposed by the VM and also call actions of the VM.
VM (ViewModel): Exposes actions, e.g. login, internally calls a Repository which calls the API (e.g. using Retrofit2), when it receives a result, it updates the data objects observed by the V.
Have a look at:
ViewModel
LiveData
Codelab
I have my MainActivity connecting by Nearby Connections 2.0 to Rpi3 with Android Things installed. And I need to start SecondActivity or ThirdActivity depending on payload I've received in MainActivity. Either second and third activities have their own PayloadCallbacks. So in order to get Payload there, I have to disconnect in MainActivity and connect again in the new activity with new PayloadCallback set in acceptConnection() method.
Is there a way to save existing connection, but change PayloadCallback?
Code can be found on github.com/Mkryglikov/BestCafe. I'm talking about ConnectActivity and ActiveOrderActivity
The typical pattern for what you're trying to do is to keep all your Nearby Connections code in one place (a class named something like NearbyConnectionsManager that all the Activities have access to), and to have all your different Activities register handlers with that class for the different BYTES Payloads you're expecting.
That way, NearbyConnectionsManager's onPayloadReceived() checks the value of the payloadString that it receives, and has a switch statement that invokes the handlePayloadString() callback method of the relevant Activity, thus keeping each Activity's logic contained within itself, while avoiding the need to disconnect and reconnect from your peers.
You may use a Service to encapsulate your Nearby Connections stuff (connection, events, errors, payloads), and allow your components like Activities and Fragments to bind and query the service (via an IBinder). Whether this service will be more persistent or short lived, it is up to your needs.
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.
it's more a general question rather than a specific one.
Basically I'm developing an Android app which communicates with Ble Peripheral Device.
I handle Ble communication using RxAndroidBle library. As for the general pattern, I decided to try Mosby MVI, however
that's not that important.
What I did so far is I created BluetoothManager class which is responsible for performing all the operations
on the Ble Device. This class is a Singleton (I know it's not recommended on Android) and I scoped it using Dagger,
that this is injected only to those interactors that should perform some Ble communication.
This class returns Observables with some POJOs, which are transformed to ViewStates in interactor and than moved higher to the UI.
Subscriptions are in the presenters following Mosby MVI pattern.
Basically thanks to that I treat this Ble Device as a regular data source, same as some retrofit service or any db.
And that was totally fine as long as I was performing atomic operations like writing and reading some single characteristics.
The problem is when I need to fire up some kind of a synchronization that may take quite a lot of time, should be done on background,
should NOT be bound to UI, however on some screens user should be able to see the progress.
Here I started to think about using Android Service and putting all the Ble Communication logic there,
however in my opinion using Android service breaks any attempts of logic separation and I couldn't find a good way to fit it there.
Third option was having a service for synchronization and preserving BluetoothManager for atomic operations bounded to UI, however
I think it's messy and I would be nice to have all the Ble stuff in one place.
I know it's long but it all goes to one question -> what would be the best pattern to follow when communicating with Ble device on Android
to preserve layers separation and keeping it as independent as possible.
I could not find any good articles about handling that, if there are any they are quite out dated, not using Rx approach.
If it's too generic, I can specify some more details, but I'm looking more for an architectural advice rather than code snippets.
What about something like this:
instead of subscribing in presenter to bluetooth directly, introduce a class BleRepository
Then BleRepository provides a metod Observable<Foo> (Foo is whatever data your Presenter / UI should see) and operations to execute stuff like doA(). Something like this:
interface BleRepository {
// Read Data
Observable<Foo> getDataObservable();
// Write Data operations
Completable doA();
Completable doB();
}
So the Presenter subscribes to BleRepository instead to bluetooth connection directly.
So now whenever you do a "write operation" you just execute it but you always read new data from getDataObservable() even if the write operation itself returns new data, reading data always goes through getDataObservable().
So BleRepository is basically just a public API your presenter uses. The Presenter doesn't know about the actual Bluetooth connection. So what you can do next is moving the actual bluetooth connection into an android service, lets call it BluetoothService. Then BluetoothService get's connected and whenever the sync runs or whatever else your connection receives / sends, it emits that data back to BleRepository.getDataObservable() which is subscribed by the service. You just have to ensure that both Service and Presenter "share" the same BleRepository instance. i.e. use dagger to inject the same instance or make it a singleton ... whatever works best for you.
Depending on your usecase you can also make the BluetoothService subscription aware like start the android service in RxJavas onSubscribe and stop the service in on unsubscribe / onTerminal. But it sounds like your usecase is slightly different so that Bluetooth is still connected even if Presenter / view has been destoryed, right? Whatever, the idea is use Service (Services if it makes sense for your proble) but they all somehow push the data into BleRepository that then delivers the data to the Presenter.
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.