I have a project that involves using an Android device to send commands to and receive messages from a remote embedded controller (similar to an Arduino) via Bluetooth SPP.
I have successfully created a single activity app based on a series of tutorials on YouTube. Much of the code in the tutorial is taken from the official BluetoothChat example but it is not done as a service.
Now for my problem... I need to set up a "Home Page" activity that will start other activities when a corresponding button is clicked.
Each activity spawned off the Home Page will have button controls to send commands via Bluetooth to the embedded controller to perform different functions.
The initial Bluetooth connection is started in my Home Page activity. When a new activity is started though, my Home Page's onStop() method is called and the Bluetooth connection is lost.
Short of duplicating the Bluetooth Code in each activity, it would seem a service is the way to go? I found this post on Stack Overflow link that is very good, but I'm new enough to Android programming that the missing details have made me hit a brick wall.
Also, the example does not address multiple activities using the service. What is the best way for me to approach multiple activities using a Bluetooth connection?
I see two options for you to achieve what you seek:
Manage your Bluetooth connection in the Service, and use the Android doc to write a working service. And you can bind each of your activities to your running service using bindService(). The service runs in background and won't stop when you go from one activity to the other. But for that you need to move most of the code you have into a service. Again, follow the doc.
Use fragments: Android Doc. And if you know nothing about fragments: Android doc. Basically, a fragment is very similar to an activity but it is recommended by Android to use fragments. You will have one activity that manages you bluetooth connection and hosts your fragments: you will replace all the activities you wanted to have in your app by fragments. So when you navigate from a fragment to the other, your activity won't be stopped and so your bluetooth connection will be safe.
I don't know exactly what you want to do, but the first option is the only right option if your bluetooth connection has to run even when the user has their phone in their pocket. The second option is better if the user doesn't need to keep a bluetooth connection when they leave the app.
Hope it's clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With