Im learning from Android's BluetoothChat sample app and noticed that they are using a Handler to send updates to the UI as seen here . I was wondering why they wouldn't prefer to use a callback/listener to send updates to UI?
My guess is because Handler posts messages on the Thread it was created on. If you were using callbacks, you would have to take care of calling runOnUiThread(Runnable) in order to perform any kind of UI changes.
For a Guess.
Handler is a perfect async solution. just post message to the MessageQueue,Handler(UI Thread) will take message from it. It can reduce your module's complexity.
CallBacks is another solution,but complex according Handler to update UI.
Related
I am using volley library to perform network operations. On Application launch, I hit the service, I want to stop all the operations until i get the response from the service.
So i want to perform this synchronously. As I am using Volley which by default works in a separate thread. So how can i do this.
I have created custom Interface/listener to handle this, but does Android provide some way to achieve this.
I have done following.
Splash Activity implements an interface, and it goes to Main Activity after data is loaded
#Override
public void onContainerLoaded() {
//startActivity(MainActivity)
}
Even if you want to, you should definitely never EVER run any network-related task synchronously.
What you can do instead is starting your activity normally, and replace your layout with a progressbar logo, that is set to visibility.gone when your task is completed.
EDIT : By the way, if you are just starting your app and you haven't done anything concrete yet, I would recommend you to use an AsyncTask instead of Volley, which is often causing layer-coupling mistakes.
Use some event bus such as Otto
Create an event, make your main activity subscribe to the event using the event bus, start your operation, display a "Loading..." or something ProgressDialog in your main activity. From your worker thread when it completes send an event to your main activity. Make your main activity close the "Loading" dialog when it receives the event,
I guess a better question would be why you want to force it on the main thread?
As far as I know, volley won't let you do that but you might be able to if you make your own network operation. After Honeycomb, you will get a NetworkOnMainThreadException so you will need to override the policies.
I am making a chat application.The server will send me an update whenever a friend sends me a message.As a result i need a continuous listener from my android client.I have used asynchronous task and in the post execute method, i have called the asynchronous task again.Thus listening continuously.But this is giving me weird errors.
If you could help me i would be really grateful.If you think i should implement the continuous listener in some other way please do suggest me.Thanks.
Proper method should be like when you get connected to server, you should keep listening in a loop. See my answer here
and modify it as needed.
What about using http://quickblox.com/developers/Android library? I am just curious, if it would not be easier :) .
Otherwise I thought about making while cycle in doInBackground() method, instead of calling asyncTask all over again.
Something like -
While(programExit) {
//your code
}
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
I'm facing this problem: after clicking on a button, I make a request to the server and get some data; then, I display the data on a new page/view. This raises a problem: the UI has to wait while the request is being made and data is being received, parsed and set on the view. This results in the user having to wait until all the data is loaded before even being able to go back, and doesn't even have the chance to cancel the call. Multithreading would solve the issue, and that's where I need help.
The HTML5 Web Workers would do the trick for me, however I don't want to "hard code" them in JSNI and have all the calls written with Javascript instead of GWT Java (RequestBuilder). I've read about DeferredCommand but I also don't think it's the answer to my issue.
Any suggestions? Or this is an impossible optimization, at the moment?
In JS, therefore GWT, there is no multithreading. Instead you should use asynchronous calls with callbacks. Normally when you use GWT RPC for communication, you issue a request and handle result in onSuccess event. Alternatively you can always use Timer to check for result periodically. I'm not sure what kind of request you are making, so hard to be specific. Probably you should check appropriate section of Communicating with the server
EDIT: I've just noticed you mention RequestBuilder. The sendRequest() should not block execution and you should process result in RequestCallback.onResponseReceived() of provided callback. Which mean you somehow continue your button event handling in that callback.
Multithreading on Android is to some extent an easy task due to the various possibilities available for us.
However it would be nice to understand the difference between the approaches.
What is the best way to multitask and based on what preferences is it the "best"?
AsyncTask?
class MultiTasker extends AsyncTask<, , >
Runnable?
Runnable myRun = new Runnable(){
public void run(){
}
};
Thread T = new Thread(myRun);
T.start();
Handler?
class MultiTasker extends Handler
Asking which one is "best" is the wrong approach here - it depends on what you are trying to accomplish.
Runnable/Thread - This is the basic, lowest-level ways to control threading in Java. Provided in the Java APIs, so they're not specific to Android. You can use these in Android programs, but you'll probably want to use one of the other two options for most tasks (or use them in addition to Threads).
Handler - Provided in the Android APIs. You can post() a Runnable directly, or sendMessage() a Message (along with other options, such as providing a delay before processing a Runnable or Message). However, Handler isn't something you would use by itself to provide multithreading - it's use is usually to get back into the main activity (UI) thread. You'd start some other Thread to do a process in the background, and inside of it would post a Runnable using the Handler when you needed to update the UI. Or if you had a task that didn't necessarily need to run in the background, but did need to pop up and do something every so often, you could post a Runnable with a delay to activate later, and then at the end post itself again with a delay.
AsyncTask - Provided in the Android APIs. This class is for doing something on a background thread, optionally providing incremental updates on the UI thread, and ultimately providing an end result on the UI thread. The Params, Progress, and Result generic types are used to provide start parameters, progress update data, and end result data, respectively. Internally, AsyncTask uses Threads, Runnables, and Handlers to accomplish this task.
Its Always better if you go with AsyncTask().. because Thats something which has been built to solve MultiThreading issues in Android..