Using a Handler in multiple Activities - android

I am developing an application which has around 8 Activities, and a class which is used to connect/receive data to/from an embedded Bluetooth chip. When I started, a Bluetooth object was initialized in my initial Activity, where there was a Handler which received messages from the Bluetooth object.
After poking around on the internet for a while, it seems like the best idea for me is to turn my class into an Application subclass. However, doing this removes the need for me to initialize an object in the MainMenu, which removes my ability to pass it the Handler used.
Does anyone know of a way to eliminate the need for a Handler, so that every time the Bluetooth Application changes it state or receives data, the current Activity can access it?
My main problem with this approach is that the Activity doesn't know when the Bluetooth Application will be sending it messages, the Application waits and listens, and then notifies the Activity when it happens.
OR
Is it bad practice for me to write the Handler into the MainMenu, have it handle messages for ALL the different activities, and then pass the Handler from Activity to Activity?

I'm going to assume that you're trying to achieve the following as it's a little unclear from your question your ultimate aim (sorry!):
Your application has several activities but only one Activity receives the data from the bluetooth device.
The other activities in in your application require the data from the bluetooth device but are not receiving it directly from the bluetooth device. Currently you're providing the data via the one activity mentioned above.
You want to NOT use a Handler to achieve this.
If my above assumptions are correct then you are going along the correct lines but you probably do not want to use a Handler.
You are quite correct in having one Activity handle all the interactions with the Bluetooth device. It simplifies things and provides a much better, cleaner way of handling the Bluetooth device. However you need to get the data from this one Activity to all the others and to achieve this you would probably want to use Broadcasts, BroadcastReceivers and Intents. See here for an overview.
However if you can you might want to take a look at using LocalBroadcastManager as this keeps any broadcasts within your own app's space. Broadcasts are global and should be avoided if you do not need to pass the data outside of your own app due to security implications.
Finally, have you considered using Fragments for your other Activities? Another disadvantage with Broadcasts is there is extra overhead associated with them. If you're keeping data within your app then you can create an interface to be implemented by each of your Fragments and your main activity just calls that interface on the Fragment that is currently selected.

You can use BroadcastReceiver class to send broadcast messages to your activities. see here http://developer.android.com/reference/android/content/BroadcastReceiver.html
When you get the data you need into the application class, you can send it to the activity you want.. just make sure that the activity has registered to receive that broadcast message..

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.

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.

Android deal with lot of intents

My app is design to get messages from an embedded Bluetooth device. While I was working with sensors which sends data each second or more, it was not such a big deal to broadcast intents to activities. The only visible slow down was when the Bluetooth device flushed its buffer.
Now I need to deal with high refresh rate sensors (such as ECG, every 2ms) so I have to be little more cleaver because the number of intents makes visualization not in real time (there is more measures incoming than displayed).
I try to work with putIntegerArrayListExtra() to send data each 2 seconds but now I get a A.N.R.
Is someone can advise me to deal with lot of intents? (It seems my service memory also grow up to much).
To bypass intents, I have to send an object from a service to an activity. As far I now this is impossible and the reason of Intent.
EDIT:
I had underestimate binding. In fact it enables activities to get from the service an instance of a "DeviceDriver" which register listeners to perform callback. As I can retrieve the instance of the driver in the activity, I can register it as a listener and cut down all intents between service and activities (At least for data exchange).
You can also use binding to pass data from service to intent:
http://developer.android.com/guide/components/bound-services.html
In your case I advice you to not use intents. Try to use thread inside activity or shared memory and synchronization.

How can I pass an event from Application to Activity in Android?

I've got a little gap in my knowledge here and I want to make sure I do it right before writing all the wrong code.
I have an Android app that extends Application to set up some core functions for a TCP client. There are a few different Activity screens that should interact with Application. What I'm stuck on, is what to do when a data packet is received by Application. I want to relay it to the currently-visible Activity, whatever it is.
Coming from a C# background, I'd just create an Event in the Application, and simply subscribe to that event when an Activity is created. But I'm getting confused with Java Listeners, Handlers, ...
What's the best way to go about that? Should I be doing a Service instead? (But I don't really care if the TCP connection is killed when the app is not shown.)
I would go with a LocalBroadcastManager (documentation) approach.
Create one of those puppies in your Application class, and register/unregister your Activity objects in onStart and onStop. See Context.registerReceiver. Note that this requires using Intents, which might be too restrictive/heavy-weight for your application; packing/unpacking data can be a chore.
Alternatively, you don't have to use any specific android class to do it--just keep track of what Activity your program is in by calls to your Application in onStart and onStop. Might help clean your code if you make all of your activities-of-interest extend a subclass of Activity that contains this logic.

Communication between Activities: Intent or Service: what is faster?

Is there a significant difference in time needed for sending data over a service or by using an intent?
Are there general advices when to use service and when to use intents?
These are two completely different things. The question isn't which is faster, but what you are trying to do.
If you want to transfer data from one activity to another, you pass it through the intent. If this is not sufficient for you (too much data for example), you can take other approaches but they will not involve a Service. For example, you may have a singleton holding your shared data, which both activities access... but be extremely careful about your process being killed at various points which causes the singleton to go away (and using a Service for this won't let you get away with not dealing with such a situation).
A Service is to do some work in the background even if the user isn't directly interacting with the app. Especially if we are talking about stuff within one .apk (and thus typically one process), there are very few other reasons to use a Service.
It depends of what you need.
Intent is preferable if you can. You will be able to send primitives from an activity to an other, and using startActivityForResult() you'll get an intent back to the caller Activity.
Service is for data processing in the background and can be very CPU/Memory consuming. With a Service, you have to create an interface between your Activity and the Service, so you can call basic methods of the Service directly from the Activity, you can control the service from the Activity.
This is really not the same purpose. Read documentation about Intents and the information you can Bundle in it, that's probably what you need.
When you want to pass data from your current activity to a new activity, the best is to pass a Bundle along with your Intent. It is used to pass on "acquired" user data.
Services run in the background while another activity is still in the foreground. "Background" doesn't mean that it doesn't display - most services have a graphic visualisation of some sort - it means that it isn't part of the activities stack. For example, your Activity may be sending a text message and your Service may be a soft keyboard. Services can communicate with activities - in this instance, your keyboard of course needs to send the characters to the text message Activity - but it often involves using a rather complex interface. It is used for collecting and passing on "live" user data to an Activity.
Many methods to pass data between activities. See here for tips on a way to choose.

Categories

Resources