Android - What is a Handler Message? - java

I'm talking about this class.
The main documentation states:
Defines a message containing a description and arbitrary data object
that can be sent to a Handler. This object contains two extra int
fields and an extra object field that allow you to not do allocations
in many cases.
So I would assume that it is some kind of communication between
different threads, maybe a Bundle?
There are also a few snippets in the main documentation. But I
can't see how are they built and what is their structure.
Why to use them instead of using SharedPreferences or maybe a Singleton class? Testing?
I would love to see a little and compact example on when and how to use them.

So I would assume that it is some kind of communication between different threads
You can attach a Handler to the main application thread (a.k.a., UI thread), and you can create separate HandlerThread instances for other threads with associated Handler instances.
One thread can send a Message, via a Handler, where the Handler will process the Message on its own thread, in the handleMessage() method. For example, a regular background Thread could package the results of its work (e.g., downloaded data) into a Message, and give that to a Handler attached to the main application thread. That Handler will get the Message in handleMessage(), called on the main application thread, and can then update the UI safely using the data from the background thread.
This is a very low-level means of inter-thread communication in Android. More often, you are better served using something a bit higher-order, like an event bus.
Why to use them instead of using SharedPreferences
SharedPreferences are for data storage, not inter-thread communication.
or maybe a Singleton class?
While a singleton can provide a central point of data, on its own, it does not provide any sort of inter-thread communication.
I would love to see a little and compact example on when and how to use them.
For 99% of Android developers, the answer is: don't use them. Use something that is built on top of Handler and Message, such as:
AsyncTask
LocalBroadcastManager
Square's Otto
greenrobot's EventBus
etc.

A Thread can have one handler and one messageQueue only, a message is some arbitrary data that is handled by the handler whom put on it's messageQueue, the messageQueue loop every message and process them until it has no more message, all data are versatile and executed asap, no need to save it on HDD, it's low level code you dont deal with it often

Related

OOA&D / Java / Software Architecture - advise on structuring event handling code to avoid a complicated data flow

I've implemented the producer/consumer paradigm with a message broker in Spring and my producers use WebSocket to extract and publish data into the queue.
A producer is therefore something like:
AcmeProducer.java
handler/AcmeWebSocketHandler.java
and the handler has been a pain to deal with.
Firstly, the handler has two events:
onOpen()
onMessage()
onOpen has to send message to the web socket to subscribe to specific channels
onMessage receives messages from WebSocket and adds them into the queue
onMessage has some dependencies from AcmeProducer.java, such as it needs to know currency pairs to subscribe to, it needs the message broker service, and an ObjectMapper (json deserializer) and a benchmark service.
When messages are consumed from the queue they are transformed into a format for OrderBook.java. Every producer has its own format of OrderBook and therefore its own AcmeOrderBook.java.
I feel the flow is difficult to follow, even though I've put classes for one producer in the same package. Every time I want to fix something in a producer I have to change between classes and search where it is.
Are there some techniques for reducing the complicated data flow into something easy to follow?
As you know, event handlers like AcmeHandler.java hold callbacks that get called from elsewhere in the system (from the websocket implementation) and hence they can be tricky to organize. The data flow with events is also more convoluted because when handlers are in separate files they cannot use variables defined in the main file.
If this code would not use the event driven paradigm the data flow would be easy to follow.
Finally, is there any best practice for structuring code when using web sockets with onOpen and onMessage? Producer/Consumer is the best I could come up with, but I don't want to scatter classes of Acme in different packages. For example, the AcmeOrderbook should be in a consumer class, but as it depends on the AcmeProducer.java and AcmeHandler.java they are often edited at the same time, hence I've put them together.
As the dependencies inside every WebSocket handler are the same (only different implementations of those same interfaces) I think there should be only one thing injected, and that will be some Context variable. Is that the best practice?
I've solved it using Message Dispatcher and Message Handlers.
The dispatcher only checks if the message is a data message (snapshot or update) and passes control to the message handler class which itself checks the type of the message (either snapshot or update) and handles that type properly. If the message is not a data message but something else the dispatcher will dispatch the message depending on what it is (some event).
I've also added callbacks using anonymous functions and they are much shorter now, the callbacks are finally transparent.
For example, inside an anonymous callback function there is only this:
messageDispatcher.dispatchMessage(context);
Another key approach here is the use of context.MessageDispatcher is a separate class (autowired).
I've separated orderbook into its directory inside every producer.
Well, everything requires knowledge of everything to solve this elegantly.
Last pattern for solving this: Java EE uses annotations for their endpoints and control functions such as onOpen, onMessage, etc. That is also a nice approach because with it the callback becomes invisible and onOpen / onMessage are automatically called by the container (using the annotation).

Is using a Observable Singleton Class to handle network calls bad?

I have to develop a client/server game that uses a lot of network request to complete its task.
Both the client and the server receive multiple Command through socket.
To handle these commands I created a NetworkHandler class that listens for new Input on a separate thread and that allow me to send new commands.
These "commands" are really heterogeneous and and are used by different classes.
(For example the "client ready" command is used by the Main server class, while the "client wants a card" is used by the Game class).
So I created a CommandDispatcher class that listens to the NetworkHandler (Observable pattern) and that dispatch the different commands to the right receivers. (All through interfaces )
The problem is that every class that wants to register as a "command receiver" need to call the CommandDispatcher to set itself as a listener.
Because there are multiple class that needs this reference I'm thinking to transform the CommandDispatcher in a singleton class that could be accessed everywhere.
I know that Singleton and global class are bad and that I'm hiding a dependency and it will be difficult to test, but the only alternative I see is passing the CommandDispatcher from the Main Class to all the other classes.
Can you help me find a better solution?
Thank you.
EDIT: I want to clarify that my app is a turn based game, so I don't have a large number of parallel request.
This is a common pattern that has been addressed many times in many environments.
The primary issue you need to address is the speed of despatch of the commands that arrive. You must ensure that no command can clog up the system otherwise you will get unpredictable response times. To achieve that you must do as little as possible to manage it's arrival.
The classic solution to this is for your network listener to do the minimum amount of work on the command and hand it off to a queue. Essentially you should merely grab the arriving message, place it in a queue and go back to listening. Don't even deserialise it, just throw it at the queue.
At the other end of the queue there can be one or more processes pulling commands out, constructing the appropriate objects and performing any functionality you want on them. This could be where your listeners should listen. Often all that will happen is the deserialised object will be despatched to another appropriate queue for handling so you may find an even more appropriate point to listen to at the other end of those queues.
Both the network listener and the command processor can often be implemented with thread pools.
Is using a Observable Singleton Class to handle network calls bad?
Bad? No - but it will not stand up to high throughput. You would be better to disassociate the network listener from the command dispatcher.

Android send data other thread queue

I want to generate some text string that is going to be sent via TCP socket . I have accomplished it within few minutes.
However I want a producer consumer pattern.I dont care if it failed or not.
Should I create a Blocking Queque at application for this ? Should I create a service ?
Note that I want a single thread to manage this job.
In the case it's a short task (like you commented), I'd recommend putting it within an AsyncTask as a background thread. You can control anything about this separately, which will help you also debugging it. Services are more intended for long executing tasks, so I'd not recommend it at this scope (it's a bit harder even to communicate with other Activity's. Here you'll find the AsyncTask's documentation, and here a good example.
The Blocking structure depends on your needs - but I don't think you'll need that in your case. Anyway, if you would need that, there're lots of thread-safe data structures you may use, you might find this helpful.
Create a LinkedBlockingQueue where your producer adds data. Create a Timer that fires every second or so. The task of the Timer would be to send the messages over the wire.
For this, both the producer (the one generating the messages) and consumer (Timer) should have access to the LinkedBlockingQueue. The Timer will remove the first element of the LinkedBlockingQueue and then send it.
Sounds good ?

Events or Handlers? Invoking methods from a thread

Consider a simple Android application: there are two TabActivities and a thread in the background getting integer values from a server. If the number is even, it must be displayed in the first tab otherwise in the second. Obviously I will be doing something more complicated, but this is the basic pattern. How do I go about doing this? I have been scratching my head for about a day now and here are things I have come across:
Use of EventHandlers. The two TabActivities register for listening for my_events and when a value is received by the thread, it 'throws my_event' and then specific methods in both these activites are called and the value is passed.
The use of Handlers.
I have not used both of these concepts before and I would like to know which might be the better/correct route to take. Further, any more tips along the chosen route will be appreciated. Also, should this thread be run from a service class?
When you create your thread just pass the objects of your tabs into it, then in your execution you can easily put the text you want into tabs.
Possibly you want to look at using an AysncTask. If you do this you want to insert the values into the appropriate tab in the onProgressUpdate() method. Since the arguments passed to this method may not actually be able to represent the incoming data sufficiently you'll just want to put the new data somewhere that it can be accessed from the onProgressUpdate() method, probably in a member variable. Keep in mind that access to this member variable probably needs to be synchronized because code in onProgressUpdate is running on the application's main thread, while code in doInBackground is running on a background thread so code in these methods will be running concurrently.
AsyncTask uses Handlers transparently for you, but you could use raw Handlers if you wanted. The basic things you need to keep in mind are
You can/should only update the UI from the main application thread
Code in a Handler will always run on the Thread that created the Handler
Handlers must be created on a Thread that has a Looper (the main Thread has a Looper)
Be careful if creating the Handler as an anonymous inner class or handing it a reference to a Context since this creates the potential for a memory leak
Possibly the Thread should be invoked by a Service, but if the Thread only needs to exist when there is a UI for it to update there may be little point to this.

Identifying Swing Threads for displaying frequent data input in Java

For my current application, I am struggling with identifying the Swing threads in my application. With Swing threads I mean:
Initial threads
The event dispatch thread
Worker threads
My application:
simple user interface which is supposed to display data received on a socket
the data is described by many model classes
the received data is XML which is parsed and the model objects are instantiated
the user interface is supposed to display the received data
these data is updated very frequently, which means the XML messages are short, but there are many of them
to put it into context: I am programming a Java profiler.
I have read the Swing tutorial so far, so here are my guesses and questions:
The background task is the server socket, respectively the background tasks are the number of opened connections on which the application receives data.
The tasks have no final result, so I guess the SwingWorker<T,S> should only define the generic type for the Interim Result? For every parsed XML I would make a call to publish. But how do I distinguish which data I have received? Maybe the XML data contains only enough information to build a class A or maybe the data contains enough information to build class A and class B, but how do I wrap both into one Interim Result? A wrapper class?
The process() method invokes changes to make it visible to the user interface, doesn't it? I don't see how this works. Where do I launch my tasks? Is it in order to invoke the SwingWorker.execute() in the JFrame constructor?
Should the XML Reader be the Task or should each Thread which handles an incoming connection be the task?
In the context you describe, I am not sure I would use SwingWorker.
My basic idea would be:
from your main(), start several threads for serving sockets (standard Thread API)
when one such socket thread gets some input, it parses the XML right away (as you describe it, parsing should be very fast, hence I don't think you would need to start a new thread just for that)
once the XML is parsed, the socket thread creates some "result object" to be displayed, declare this object in a final variable, and call SwingUtilities.invokeLater() to display this result in your UI
Another alternative that I have used successfully in the past would be to use an EventBus that would take care of callingthe UI update method in the EDT, your socket threads would send the "result object" to that EventBus.
About SwingWorker use, I would say the main use is when the end user starts an action (e.g. by clicking a button or a menu item) and this action is long and should be processed in background, the background processing method would then have to feed back information to the UI.

Categories

Resources