I'm new to Android and Java and I'm trying to use loopj's Android Async Http Client. I don't understand all the technical nuances of the introduction the library states: "All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created".
For instance, why is having the callback logic executing on the same thread as it was created important/useful? What is that opposed to? What other alternative threads could the callback logic can be executed?
Thanks in advance.
For instance, why is having the callback logic executing on the same
thread as it was created
The main reason it the UI. Only the original thread that created a view hierarchy can touch its views. This means that your application will crash if a different thread tries to update the UI
What other alternative threads could the callback logic can be
executed?
this is strongly implementation-dependent. For instance the callback could be executed on the same thread which performed the async call
I can see that execution happening on the same Thread good for at least one situation. The UI can't be modified from outside the UI Thread, so in the case you make a connection and get some data that you want to display in a EditText it is helpful to have the callback executing on the same UI Thread (Assuming you created the callback in such Thread).
Related
Can someone explain what's the message queue in Android? Is it the list of processes running? I can't find a good source explaining it.
I am asking because I was reading about the method post of the class View.
POST
added in API level 1
boolean post (Runnable action)
Causes the Runnable to be added to the message queue. The runnable
will be run on the user interface thread.
Thank you in advance.
In simple terms a MessageQueue is a list of tasks (Messages, runnables) that will be executed in a certain thread. The Android system has a very known main thread (the UI one). The method you just saw simply adds a runnable to the list of processes that will be executed in the UI thread. Alongside with Looper and Handler, MessageQueues are part of the bulding blocks of threading in Android and they are used virtually everywhere in the system.
When would you use this method?
Whenever you want to update some UI element (View element) from another thread. Maybe you're doing some heavy lifting in another thread and want to update the UI element, you can't update the UI elements in others threads but the UI thread so you post changes to be executed in the UI thread.
You can learn more about MessageQueues here and here.
to Understand MessageQueue, you need understand executing model of android app;
Just like Javascript, Cocoa in iOS, to avoid cocurrency access racing, many App related framework adapts a single thread model.
that means there is a main thread, you put your work that need be done into the queue(MessageQueue) dedicated to this thread, there is a worker(Looper) that will reteive your work from the queue, run them one by one;
this model avoid cocurrency collision in the app;
when you need do a longtime job , you should put the work into the main thread queue, when it's to do your work in the message , you create a new thread to do this longtime job, after job is done , you put a new message into the main thread message queue from your new thread;
this picture will help you understand the running model
I'm using a worker thread in my app so it's vital for me to know which code can be run from the worker thread and which code needs to be run on the UI thread.
In the Android documentation, the following hints can be found:
So, you must not manipulate your UI from a worker thread—you must do
all manipulation to your user interface from the UI thread. [...]
However, note that you cannot update the UI from any thread other than
the UI thread or the "main" thread.
(source)
But what "manipulation to your user interface" means in practice is often not as clear as it seems. Of course, it's clear that you cannot hide views, manipulate button texts, add list view entries, etc. from a worker thread.
But what about calling setRequestedOrientation() from a worker thread, for example? Is that allowed or does it fall under UI manipulation and thus must be called from the UI thread? Is there any way to tell or should I stay safe and better run the code on the UI thread when in doubt?
In general you should take guidance from the API documentation. For example the Activity.onCreate() explicitly states that:
This method must be called from the main thread of your app.
For the example you gave Activity.setRequestedOrientation() there is no explicit statement that the method should be called on a particular thread. Usually if threading is of concern the documentation will state that.
If you would prefer certainty then you called also call upon Activity.runOnUiThread()
I am trying to implement an Android app as cleanly as possible.
To this end, I have defined a Java library for doing my logic and non-Android specific functionality.
For example, my app does a lot of network calls to REST apis and generates models and validation.
The library is using Retrofit and it handles asynchronous calls. However, now I need to chain calls and this means either:
Callback from first call triggers next request (potentially leading to 'callback hell').
Entering on the UI thread by default, create a new thread to do the requests, but then I need to be able to join the UI thread again when returning to the caller.
I'm not keen on (1) as we already have code like this and its a mess.
(2) would be my preferred option if there was a way to get a reference to the incoming thread (UI thread), then be able to join it again when the models are ready to be returned.
Is this possible?
To run anything on a thread you need some kind of a message loop. The UI thread is a part of Android and I guess it's impossible to run something on it without access to Android classes.
It's easy to get the UI thread using system API. Then you can post runnables to be run on that thread.
new Handler(Looper.getMainLooper()).post(new Runnable(){
public void run(){
// your code
}
});
You could use an AsyncTask to accomplish this. An AsyncTask is, as the name suggests, an asynchronous class that has both a doInBackground method, which executes in the background similar to a Thread, and a onPostExecute method, which runs on the UI and allows you to perform any UI-related activities. More information on AsyncTask may be found here: http://developer.android.com/reference/android/os/AsyncTask.html
I was wondering is it ok to execute a Thread inside the doInBackground method of Asynctask. Should I avoid using this kind of structure on my codes? And if yes, why should I avoid it? Would this cause any ineffectiveness in my apps?
In principle, there's no problem with starting a thread in the doInBackground() of an AsyncTask, but sometimes you see this done not because it's the right thing to do, but because of a misunderstanding about how AsyncTask works.
The point is that doInBackground() will automatically get executed on a background (non-GUI) thread, without you needing to create a thread for it yourself. That, in fact, is the whole point of an AsyncTask. So if you have a simple, linear task that you want executed in the background, you do it with an AsyncTask, and you don't need to do any manual thread creation.
Where you might want to start a new thread in an AsyncTask is if you want your background task to use multiple threads to complete. Suppose that you were writing an app to check the online status of various servers, and display something about their status on the screen. You'd use an AsyncTask to do the network access in the background; but if you did it in a naive way, you'd end up with the servers being pinged one by one, which would be rather slow (especially if one was down, and you needed to wait for a timeout). The better option would be to make sure that each server was dealt with on its own background thread. You'd then have a few options, each of which would be defensible:
Have a separate AsyncTask for each server.
Create a thread for each server inside the doInBackground() of your single AsyncTask, and then make sure that doInBackground() doesn't complete until all the individual threads have completed (use Thread.join()).
Use a ThreadPool / some kind of ExecutorService / a fork/join structure inside your single AsyncTask, to manage the threads for you.
I would say that with modern libraries there is rarely a need for manual thread creation. Library functions will manage all of this for you, and take some of the tedium out of it, and make it less error-prone. The third option above is functionally equivalent to the second, but just uses more of the high-level machinery that you've been given, rather than going DIY with your thread creation.
I'm not saying that threads should never be created manually, but whenever you're tempted to create one, it's well worth asking whether there's a high-level option that will do it for you more easily and more safely.
is it ok to execute a Thread inside the doInBackground method of
Asynctask.
yes it is but it really depends on your application and your usage. for example in a multithread server-client app you must create for each incoming clients one thread and also you must listen on another thread. so creating thread inside another is ok. and you can use asynctask for listening to your clients.
Should I avoid using this kind of structure on my codes? And if yes,
why should I avoid it?
If you design it carefully you do not need to avoid, for example make sure that on rotation you do not create another asynctask because for example if your user rotates 5 times you create 5 asynctasks and in each of them you create a thread that means you will get 10 threads, soon you will get memory leak.
Would this cause any ineffectiveness in my apps? Can you explain
these questions please.
I answered it above, I think better idea is using Thread Pool to minimize number of creating your threads or wraping your asynctask in a UI less fragment so you are sure you have one asynctask regardless of whats going to happen.
In any higher programming language, there is concept of multi-tasking. Basically the user needs to run some portion of code without user interaction. A thread is generally developed for that. But in Android, multi-tasking can be done by any of the three methods Thread and AsyncTask.
Thread
A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its run() method.
The other is providing a new Thread instance with a Runnable object during its creation.
A thread can be executed by calling its "start" method. You can set the "Priority" of a thread by calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.
If you use Java threads then you need to handle the following requirements in your own code:
Synchronization with the main thread if you post back results to the user interface
No default for canceling the thread
No default thread pooling
No default for handling configuration changes in Android
AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
1. onPreExecute()
Invoked on the UI thread before the task is executed
2. doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
3. onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
4. onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html http://www.mergeconflict.net/2012/05/java-threads-vs-android-asynctask-which.html
I would say there is no problem in doing that if you need something to run concurrently beside the AsyncTask.
One issue could be one of readability (using 2 different ways for concurrency), but I really can't see the harm in that - especially if one of the tasks needs to show it's result in the UI and the other one doesn't.
I'm using multiple lists embedded one inside another. This obviously slows down the App, thus I thought of using multi-threading. Treating separate lists as threads, and then the data loaded inside them as separate threads to make it faster.
Is this a better way to do it? Can I've certain examples based on it? Or even links?
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
It is better to use an async task to load a listview so you dont block the main UI
Your question title does not match the question body, you'll get better responses if you change them to relate better.
See the following question for an explaination of the differences: How to know when to use an async task or Handler
That said, in your case, you want to parralelize the population of the listboxes as opposed to the handling of messages, so AsyncTask makes most sense.
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler can be created from any thread and it runs on the thread which created it.
It handles and schedules messages and runnables sent from background to the thread which created it
.
We should consider using handler it we want to post delayed messages or send messages to the MessageQueue in a specific order.
AsyncTask is always Triggered or created from main thread.
Its methods onPreExecute(),onPostExecute(),onProgressUpdate() runs on main thread(or UI thread) and doInBackground() runs on worker thread(or background thread).AsyncTask enables proper and easy use of the UI thread.
This class allows to perform background operations and publish results on the UI thread .
We should consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.