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
Related
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).
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.
Hopefully someone can explain this to me or point me to a resource I can read to learn more. I am building an app that uses a ListView and a custom list adapter that I modeled off one of the many tutorials available online such as this one:
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
It worked fine. However, every example of how to do this runs the process of building the list of objects to be displayed and collecting the required data on separate threads.
I want to know why/couldn't you just put everything into onCreate? I can't see a reason why you would need separate threads to make this happen. Is there some general form/standard for when/what must me run on certain threads?
The Android docs on this are very good, as with most things.
The upshot is: the UI should always be responsive. So if you have some operation that will take enough time that the user will notice, you might want to consider not running it in the UI thread. Some common examples are network IO and database accesses. It's something of a case-by-case basis though, so you have to make the call for yourself a bit.
Well, if building the list of objects is not a relatively short process, doing it in onCreate() would be blocking/slowing the main thread. If you use a separate thread, it will allow the android os to load all of the UI elements while you are waiting for the list to be populated. Then when the list of objects is ready, you can instantly populate the already initialized UI, as opposed to waiting to initialize the UI until after the list of objects is built. It ensures that your application will always be responsive for the user.
Because you only have 0.5 sec to execute onCreate — after which the dreaded ADN (application not responding) error message is displayed. So unless your list view is super simple you won't make it it in time. And even if your list view is super simple it is better to learn it the proper way.
BTW: I don't even use threads, I use one or more Services to do all the work. Even more difficult to implement but more robust and responsive as well.
The reason you don't do things in onCreate or on the UI thread is for responsiveness. If your app takes too long to process, the user gets shown an App Not Responding dialog.
my teacher once said: every software can be written in a single (big) for loop.
And if you think: it can be... maybe at NDK level.
Some SDK developers wanted to make the software developers tasks easier and that's, why exists the SDK's and frameworks.
Unless you don't need anything from multitasking you should use single threading.
Sometimes there are time limitations, sometimes UI/background/networking limitations and need to do stuff in diff threads.
If you see source code of Asyntask and Handler, you will see their code purely in Java. (of course, there some exceptions, but that is not an important point).
Why does it mean ? It means no magic in Asyntask or Handler. They just make your job easier as a developer.
For example: If ProgramA calls methodA(), methodA() would run in a different thread with ProgramA.You can easily test by:
Thread t = Thread.currentThread();
int id = t.getId();
And why you should use new thread ? You can google for it. Many many reasons.
So, what is the difference ?
AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.
What Handler and AsyncTask really help you with?
The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn't thread-safe (in most of time), in other words, DANGEROUS.
That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.
Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers
I want to emphasize on two points:
1) Easy use of the UI thread (so, use when caller thread is UI Thread).
2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).
There are many things in this post I haven't said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..
#: when you read Android document, you will see:
Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue
They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue emty. (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that, Handler can communicate with caller thread in safe-way)
I have 2 questions in terms of android development and threads
1) When do you think I should use threads in android development?
2) If I have the main UI thread waiting on some variable to be set before it displays a toast, then I thought about having a while(true) loop in a sperate thread that keeps checking that variable. Now if the variable is set, how do I call the method on the first thread (The UI thread) that will display a toast
Thank you so much
Using threads directly is not necessary in most cases. The android facilities for threaded programming are great, and easy to use.
You have about three options to call the UI thread from another thread:
Handler - set an handler on the other thread from the UI thread, and send it a message when need.
AsyncTask - Perform the main task in background, but modify the UI before, during and after completion.
PerformOnUiThread - call this method with a runnable to modify the UI on the UI thread.
Good article to read about is Painless Threading.
Never have a while(true) loop that continuously runs. It'll burn massive amounts of resources and, in your case, accomplish very little.
Threads are good to run for (mainly) background tasks and resource intensive tasks (so that you don't block the UI thread). To create a new Thread, use the following:
new Thread(new Runnable(){
public void run(){
//do stuff here.
}
}
).start();
You can also look into the Android AsyncTask to avoid using Threads directly.
Depending on the type of app you are working on/with, proper use of Theads can be key to having a fast and responsive UI.
Key Rule:
If you need to to anything that accesses the filesystem, network, image loading, or anything that requires more than simple value or state checks, immediately launch and perform that effort in a thread. As already stated here, a number of options are available, although myself I usually use:
change_UI_if_needed_to_indicate_click_response();
new Thread(new Runnable(){
do stuff here ;
}).start()
You can also use standard (non-inline) thread objects like this.
That may be bad practice, I don't know. Anyway, it works well for me, and isn't really the point of your question.
If you want to run something on the UI thread using standard Java, instead of specialized Android object that specifically allows for such things, there is a post(Runnable) method attached to each and every view. For me, that's the easiest my to get code back onto the UI thread.
myView.post(new Runnable{
codeForUI();
});
My general rule is to try to never run anything on the UI thread that does not need to be there. Hope that helps.
You must use thread, if you want to prevent application from the current error or crash "Application not responding".
i use it when i call web services, geolocations.
Good frensh article:
http://souissihaythem.blogspot.com/2011/08/application-not-responding.html
http://souissihaythem.blogspot.com/2011/08/application-not-responding-solution.html
I want to create separate threads for implementing the core logic and updating the GUI.
Both threads should not share data with them directly. For this, i want to create a vector queue with synchronized get() and put() methods.
Suppose if an onClick event happens in the GUI thread, it notifies the core thread that it received the OnClick event. So the core thread implements something and puts the result in the vector. At this point, the GUI thread is notified of the received result and it fetches it and updates the screen.
I cant figure out how to do this. Is there a way this could be implemented?
You can do that as you would in any other framework or environment. The Android api offers you a lot of high level ways of handling multithreaded applications like you described (AsyncTask, Handler/Thread/Runnable, etc), but you can also wrap these in your own processing queue. I've done that recently where I created a logical queue for processing, and when I push something to the queue, I run a method that checks my queue for items and processes them on a background thread. You can notify the system when your processing is complete by sending broadcast intents and registering IntentFilters at the Activity level (don't forget to unregister) or you can implement your own listener interfaces the way the Android UI framework does with UI events on Views
At the heart of it though, however you wrap it, AsyncTask makes it really easy to call back and forth between background threads and the main UI thread. onPreExecute, onProgressUpdated and onPostExecute all run on the UI thread and doInBackground runs in a background thread that is automatically created for you. Doesn't get any easier than that