Hi guys I have a question about Asyntask which is used in android studio :
As far as I know AynTask is used for user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished.
But let's say that I want to register an account so that I can login, that shouldnt take time at all so why should I use Asyntask for this?
Let's say I want to send 100 strings to the Database, that can be done in milisecs I think, so again, why to use and how to decide when to use Asyntask?
I hope you guys can help me out, I have been searching for a long time !
If you don't know how much time operation will take, you should perform it in a separate thread and then pass the results to UI thread. I think the database should be accessed in a separate thread as well as HTTP requests. In the case of time-consuming query, it may be a long operation. AsyncTask is one way to do it. You can also use other techniques. The popular technique used nowadays is applying RxJava library, which gives you the high-level functional reactive interface for writing multi-threaded applications with a few additional features. You can perform an operation in e.g. Sechdulers.io() (I/O) thread and then pass the result to AndroidSchedulers.mainThread(), which is UI thread.
There are also other techniques like using Looper & Handler from Android SDK or using Thread class from Java, but such techniques require more knowledge, more work, writing more boilerplate code & you have more problems to deal with.
Related
As I understood, Firebase Database performs all the reading tasks on a single thread.
Is there a way to split that work into few different threads?
Is there a way to make a tasks execute before another? some parallel to handler.postAtFrontOfQueue() ?
The Firebase client handles all network and disk I/O on a separate thread to avoid interfering with the UI of your Android app. The callbacks into your code are invoked on the main thread, so that your code can interact with the UI.
The operations are executed in the same order in which you call their APIs. There is no way to re-order operations. There is also no way to set up multiple threads, nor have I ever seen a need for that. Interacting with a remote service is inherently an I/O intensive operations, which is not helped by multi-threading.
This sounds like a XY problem. If you describe the actual problem that you're trying to solve, we may be able to help better.
I have looked through many examples/tutorials of using SQLite in Android. Let's say you have an app that uses SQLite, ContentProvider, CursorLoader, a custom CursorAdapter.
Now all major examples of this that I've found rely on a CursorLoader to fetch data to the CursorAdapter, which by the nature of CursorLoader happens in an Async - UI thread safe manner. However, these same examples all make insert/delete/update calls through the ContentResolver on the main thread (e.g. from onClick, onResume, onPause). (Example) They don't wrap these calls in an AsyncTask or launch a separate thread or use the AsyncQueryHandler.
Why is this, how can so many well written blogs/examples make such an obvious mistake? Or are simple single row insert/delete/update calls so quick that they are safe enough to launch from the Main/UI thread? What is the proper way to do these quick calls?
I also got confused about the samples making calls on the main thread. I guess the samples just simplified the demonstrations avoiding extra threads and callbacks, since single insert/update/delete call may return quickly.
Besides the Loader pattern for query, android did provide a helper class AsyncQueryHandler, since API level 1, for async CRUD operations with full CRUD callbacks supported. The AsyncQueryHandler works inside with a HandlerThread for the async operations and delivers the results back to the main thread.
So I do believe the ContentProvider queries should run in worker threads other than the UI, and those samples may not be best practices according to the official design.
=== edit
Found an annotation from the official framework docs, see this or this, Line 255:
In practice, this should be done in an asynchronous thread instead of
on the main thread. For more discussion, see Loaders. If you are not
just reading data but modifying it, see {#link android.content.AsyncQueryHandler}.
=== edit 2
Link to actual android dev guide containing the above quote
This question has been on my mind since a long time. I guess, this depends on the complexity of the file we are trying to Insert, Update or Delete. If our application is going to Insert or Update large files, it would be always right to do it asynchronously and if the files aren't going to be that big, running it on UI thread can be done.
However, it is always recommended to continue with Database operations on a separate thread.
I think you've answered your own question. I do believe CursorLoader extends AsyncTaskLoader. Calls made from UI thread only process the call TO the CusorLoader (which uses AsyncTask.) What is being done BY the call still does not occur on UI Thread. Making a call to a method/function that then runs things on a seperate thread is still doing work away from UI thread.
What work do you think is happening on the UI thread?
Please show Debug log if possible or example where you think work is done on UI.
It shouldn't be.
Not trying to argue just want to know how you've come to the conclusion of UI work?
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 am new to android development. Currently i am working on an application which will take a query from user, send the query to the server and will receive an XML response in return. Then it will process the xML response using XMLparser, will extract the answer from XML response and display answer to the user. Since all this processing takes some time, i want to show a progress dialog to the user for the processing time it takes.
I have gone through some ways of doing this like i can use AsyncTask, Handler or Runnable (java) threads. But as much I have read about all these, I have got confused which one to use.
Please tell me which one is better to use for above mentioned scenario. And a simple way to implement the preferred one.
Thank You in advance.
I'd recommend you to use AsyncTask because it is simplier than other approaches and it suits your needs.
I think you mess a bit these three different entities:
AsyncTask runs a set of actions in a separate thread, can show progress during its work and show notification when the task is completed.
Runnable is a command that can be performed. You should run in a separate thread. Also you should develop a logic in this case how to update progress and how to notify when the task is finished.
Handler is a special class that can handle messages that are sent to the handler's thread.
From http://developer.android.com/reference/android/os/AsyncTask.html :
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed for a use very similar to yours.
Runnable is only to run a block of code on another thread:
Represents a command that can be executed. Often used to run code in a different Thread.
(http://developer.android.com/reference/java/lang/Runnable.html)
Handler is used more for Message Queuing. Your case doesn't seem to require messages being sent repeatedly.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
http://developer.android.com/reference/android/os/Handler.html
Note that neither Runnable nor Handler talk about displaying the results back on the UI thread. That is where AsyncTask helps you more than either of these.
It may be my personal preference - but I would use AsyncTask in your case. It provides all necessary controls for starting up the task, updating progress as necessary, etc. I have a very similar requirement in my app (send request to server, get response in XML, parse response, do something with the data) - I'm using AsyncTasks for this purpose.
As far I know AsyncTask is the recommended way. I think is the easiest way to implement and the more "Android best practice" for asynchronous tasks.
Could you refer to this question
Here's how I see it.
Handler is more for queuing many actions, and gives a bit more control. It's better for repetitive tasks which are generally not restricted to the UI.
AsyncTask provides a simple way to do background processing, not caring much about the lower-level stuff. It's great for relatively small, individual UI updates.
IMO, you should use AsyncTask. That being said, it's kind of a toss-up.
I think it's a matter of self-preference, but in your case I would go for the AsyncTask because it facilitates the interaction between the UI thread and the background thread.
I'd use a combination of AsyncTask and Handler, because please remember that you cannot change the UI from outside the UI thread (in this case you cannot intervene and show the answer to the user).
To overcome this, I ran the AsyncTask and catched the result with a custom callback method, which simply encapsulate it inside a Message and sends it to my custom Handler, which is inside the UI thread and can safely render on-screen my result.
AsyncTask might be the choice,because it provides all necessary controls for starting up the async task, updating progress bar, etc.
But, the point is AsyncTask is the best solution to the scenario.
Handler or Runnable are more suitable to duplex cases, like chat apps.
Can anyone give me a clear description of what is AsyncCallBack? Does it exist in the latest android version? Because I am directed to AsyncTask when I search for AsyncCallBack.... Are these both same? Does anyone have an example?
Thanks in advance.
There is no class named AsyncCallback in android. I think what you are looking for is AsyncTask which is a way to run a piece of code on another Thread so the UI won't be blocked, and receive it's results on the UI thread. For example, say you want to talk to a server on the internet in response to the user clicking something in the UI, then receive some result from the server, and update the UI. AsyncTask makes doing this very easy compared to doing regular threading code because threading lifecycle and communication back to the UI thread is handled for you. As a bonus there is also support for canceling a background task, but you have to write the code to handle it when cancel is called. It doesn't do it without some work on your side.
I think the terms may be mixed up here, there isn't an AsyncCallback in Android (as far as I know). There is however very widely used AsyncCallback interface in GWT (Google Web Toolkit): http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/user/client/rpc/AsyncCallback.html.
In Android you use AsyncTask to easily run background operations asynchronously on a separate Thread from the main UI/app thread: http://developer.android.com/reference/android/os/AsyncTask.html.
Here is a good intro article on AsyncTask: http://developer.android.com/resources/articles/painless-threading.html.