Keep connection alive? - android

In bluetooth chat example, I want to add another activity. When the connection is made and when the new activity is loaded, how do I still keep the connection alive??
After I load new activity, the onStop method is called and I canned send message using the connection made before. I tried the following code in my new activity:
BluetoothChat bt = new BluetoothChat();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.special_keys);
bt.sendMessage("hello");
}
I manage to send the 'hello' but it force closes after that.. There must be an efficient way to handle this situation. Please help.
Thanks in advance.

I have recently created an Android application that communicates to a hardware device over Bluetooth. In my application, I have many Activity classes that communicate through the connection, and the application also performs continuous data logging from the connection in the background, too. Therefore, hopefully I might be able to help here. (This is my first attempt at posting an answer on StackOverflow, so go easy on me.)
In my application, I have first of all put all of the Bluetooth code into a separate dedicated class file (which I call BluetoothIF.java). The constructor in this class performs basic adapter initialization, and further methods are provided for tasks like making connections, etc. It contains the Runnable classes for establishing a connection and then transmitting / receiving over the established connection. (Essentially it is based upon the BluetoothChat example.)
I don’t need to perform a massive amount of communication over the Bluetooth connection, and I also needed to have a Service in the background to continuously monitor and log data from the connection as previously mentioned. So, I instantiated my BluetoothIF within the Service. Any Activity classes that need to exchange data over the existing Bluetooth connection do so in my application by exchanging messages with the Service.
Alternatively, if you have no need for using a Service, perhaps you should share the Bluetooth object instance across Activitys using the singleton model or by extending the Application class.

Related

Update existing PayloadCallback in Nearby Connections without reconnecting

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.

Bluetooth connection from phone to Bluno disconnects when app goes to another activity

My goal is to connect my app to a Bluno module. I used and tweaked the codes from this tutorial. Basically my version's launcher activity has a "SCAN" button that lets me scan and connect to the Bluno module. Once connected, it redirects to another activity (which is kind of like the "main" one in a sense that the features are here i.e. chatting, contacts, calls). Problem is, once I've successfully connected and redirected to the other activity, the Bluetooth connection disconnects. How do I fix this? Thank you.
Looking at the library example, the problem is probably that if you just copied it straight up then going to the different activity will pause as the BlunoLibrary is written to be an activity class that you extend. Frankly it is a little bizarre - and as an example it is not very helpful for practical use if you intend to have multiple activities or for some reason can't subclass from that, it's also straight up designed to not run in background.
Specifically if you look at
public void onPauseProcess() {
System.out.println("BLUNOActivity onPause");
scanLeDevice(false);
mainContext.unregisterReceiver(mGattUpdateReceiver);
mLeDeviceListAdapter.clear();
mConnectionState=connectionStateEnum.isToScan;
onConectionStateChange(mConnectionState);
mScanDeviceDialog.dismiss();
if(mBluetoothLeService!=null)
{
mBluetoothLeService.disconnect();
mHandler.postDelayed(mDisonnectingOverTimeRunnable, 10000);
// mBluetoothLeService.close();
}
mSCharacteristic=null;
}
in BlunoLibrary(or the onDestroy, or the onStop) you'll see that it disconnects the service when you switch activity. you could just not call this(from mainactivity), but then you would need to pass that old activity to the new activity object or at least somehow inform the old one where to send incoming messages. Frankly you would be better off just looking from the BlunoLibrary.java what it actually does(to make the bluetooth connection) and making your own based on that information and then you can make it into a service or however you want so that it survives switching of the activity.

Android app architecture with BLE

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.

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.

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

Categories

Resources