Android operations and threads - android

I'm currently writing and android app, and I was using HttpClients and those classes. I spent 2 hours trying to fix some errors until I read a post that said that you cant do that operation in the main thread. So they suggested I use AsyncTask.
So My question is, how do I know which operations should be done in a different Thread? is there a list where I can read them?
Any information would be good, thanks in advance.

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:
Opening a Socket connection (i.e. new Socket()).
HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
Attempting to connect to a remote MySQL database.
Downloading a file (i.e. Downloader.downloadFile()).
If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

The network exception is the only exception that will be thrown in android by blocking the UI-Thread. So you have to keep 3 rules in mind by programming in android.
Don't let the UI-Thread handle operations that will take more then 5 seconds to complete.
Don't let a broadcast receiver handle operations that will take more then 20 seconds to complete the onReceive ().
And don't handle network operations in the UI-Thread.

As other answers have said, Android is not thread safe, meaning:
You cannot manipulate the UI from a Background thread
You cannot do heavy tasks on the UI thread
Other operations of this sort could include processing large amounts of data/ database manipulation/HTTP requests/Network management. Really, I believe anything that doesn't require the UI thread but does involve large processing time should be moved to a seperate thread.
This makes logical sense, because if you were to do heavy processing, the user would feel a lag and User Experience would be compromised (and, ofcourse, could definitely be used to overload the system,etc.) Therefore, the system will kill the process and throw an error post-honeycomb.
As a result, you want to use an Async Task.
An Async Task really just opens a new Thread on which you can execute heavy processing or Network Connections. For Network Connections, I recommend the use of AsyncClients like this one that implement AsyncTask in an easier format for you to use. There are also libraries like UniversalImageLoader that will allow you to load Images into Grids/Lists.
I also highly reccomend you read the official Android documentation discussing this and there is a useful post on the Android blog about this as well. Lastly, I feel as if this post might be useful to you because it may include the error you encountered (Error because you performed the operation on the UI thread).
Other Resources I've found:
CommonsWare's Service
This StackOverflow Question has some good solutions.
In conclusion, here is an example of an AsyncTask being used. (nicely put answer from #Graham Smith).

Anything that takes a lot of time should be done in another thread. This includes large IO and network access. However I think only network access will throw an exception, anything else would cause an unresponsive UI. Although if you take way too long you'll trip a watchdog timer and the app will be killed.

As Gabe mentioned, you should do heavy tasks in separate threads.
there are two important things about android threads.
1 is the common threads..(the thread that do what you ask)
2 is the ui thread...(the thread that listens the user inreaction and draws ui)
you can change ui(Views act) only by ui thread.
on the other hand after honeycomb it is forbidden to do http requests in main thread.
(it is called strict mode)
in short, any operation that blocks user interaction should be done in another thread.
i hope this helps you.

Related

Android AsyncTask vs Thread + Handler vs rxjava

I know this is the question which was asked many many times. However there is something I never found an answer for. So hopefully someone can shed me some light.
We all know that AsyncTask and Thread are options for executing background tasks to avoid ANR issue. It is recommended that asynctask should only be used for short-running tasks while thread can be used for long-running tasks. The reasons why asynctask shouldn't be used for long tasks are well-known which is about the possible leak caused by asynctask since it may continue running after an activity's destroyed. That is convincing. However, it also leads to some other questions:
Isn't thread also independent from activity lifecycle? Thus, the risk with asynctask can also be applied to thread. So why thread is suitable for long-running tasks?
Looks like the risk of asynctask is only applicable when using it with activity. If we use it in service (not IntentService since IntentService stops after its work's completed), and as long as we can guarantee to cancel the asyntask when the service's stopped, can we use it for long-running tasks? and doesn't it means it's risk free to use asynctask in services?
I've played with rxjava for a while and really like it. It eliminates the need of worrying about threading (except you have to decide in which thread to subscribe and observe the emitted data). From what I can see, rxjava (in conjunction with some other libs like retrofits) seems to be a perfect replacement of asynctask and thread. I'm wondering if we could completely forget about them or there is any specific case that rxjava can't achieve what asynctask and thread can do that I should be aware of?
Thanks
Since no one's replying. I'm answering my own questions then.
The reason why AsyncTask is recommended for only short tasks (around 5 seconds) is there is no method to cancel a running AsyncTask. There exists a method called AsyncTask.cancel(true) which invokes onCancelled(Result result). However, according to the docs, this method "runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished." (https://developer.android.com/reference/android/os/AsyncTask.html). On the other hand, Thread can be stopped with Thread.interrupt().
There shouldn't be any problem running an AsyncTask within a Service provided that you are aware of the cancellation limitation of AsyncTask and the possibility of memory leak can be created by AsyncTask. Note that, there is obviously no need to use an AsyncTask in an IntentService which is already running in a worker thread.
This is a very experience-based question. I guess there would be no complete answer. What we can do is to understand Rx and being aware of the its limitations to determine where suitable to use it. In my development work, I use RxJava all the time without having any issue. Note that the same memory leaking issue is also applied to RxJava. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation with RxJava that can be easily found by Googling.
AsyncTask and Thread+Handler are not carefully designed and implemented. RxJava, Akka and other frameworks for asynchronous execution seem more carefully developed.
Each technology has its limitations. AsyncTask is for a single parallel task with ability to show progress on UI. However, if activity is regenerated (e.g. because of screen rotating), connection to UI is lost (one possible solution for this problem is at https://github.com/rfqu/AsyncConnector).
Thread+Handler keeps memory for thread stack even when there is no messages to process. This limits the possible number of threads. You can have much more Akka actors or RxJava Subscribers than handler threads, with similar functionality.

Android Firebase database threading

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.

asynctask doInBackgound() not running if there's a asynctask already running

When the user logs in into my app. I am starting an asynctask to maintain the user session. And that async task is running indefinitely till the user logs out. My problem is that when I try to start other asynctasks, their doInBackground() method is never executed.
I read somewhere that if an async task is already running, we cannot start new async task. I can confirm this because when i removed the user session async task, it worked properly. Is there a workaround?
P.S.: I have already used executeOnExecutor() method. but it didn't help.
For potentially long running operations I suggest you to use Service rather than asynctask.
Start the service when the user logs in
Intent i= new Intent(context, YourService.class);
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);
And stop the service when the user logs out
stopService(new Intent(this,YourService.class));
To get to know more about Service you can refer this
Service : Android developers
Service : Vogella
To know more about asynctask vs service you can refer this
Android: AsyncTask vs Service
When to use a Service or AsyncTask or Handler?
I read somewhere that if an async task is already running, we cannot start new async task.
Yes,That is fact that you can't run more then 5 (five) AsyncTaskat same time below the API 11 but for more yes you can using executeOnExecutor.
AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously.
I have figure out Some Threading rules and i found one major rule is below ,
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
What is definition of AsyncTask?
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.
How & Where use it?
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended to use it.
Why you can't use multiple AsyncTask at same time ?
There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Running multiple AsyncTasks at the same time — not possible?
Test sample of parallel excution of AsyncTasks
Try Executor
You should go with Executor that will mange your multiple thread parallel.
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
Sample Example 1
Sample Example 2
Just like a few others here, I object to the premise of the question.
Your core problem is that you are using an AsyncTask to perform a task beyond its scope. Others have noted this too. Those who offer solutions that can mitigate your problem through low-level threads (even java.util.Concurrent is low-level which is why Scala uses Akka actors as an abstraction), Service, etc. are quite clever, but they are treating the symptom rather than curing the disease.
As for what you should be doing, you are not the first to want to maintain a user session in an Android application. This is a solved problem. The common thread (no pun intended) in these solutions is the use of SharedPreferences. Here is a straightforward example of doing this. This Stack Overflow user combines SharedPreferences with OAuth to do something more sophisticated.
It is common in software development to solve problems by preventing them from happening in the first place. I think you can solve the problem of running simultaneous AsyncTasks by not running simultaneous AsyncTasks. User session management is simply not what an AsyncTask is for.
If you are developing for API 11 or higher, you can use AsyncTask.executeOnExecutor() allowing for multiple AsyncTasks to be run at once.
http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor, Params...)
I'll share with you, what we do on our App.
To keep user Session (We use OAuth with access/refresh tokens), we create a Singleton in our Application extended class. Why we declare this Singleton inside the MainApplication class? (Thats the name of our class), because your Singleton's life will be tided to the Activity that has created it, so if your Application is running on low memory and Garbage Collector collects your paused Activities, it will release your Singleton instance because it's associated to that Activity.
Creating it inside your Application class will let it live inside your RAM as long as the user keeps using your app.
Then, to persists that session cross application uses, we save the credentials inside SharedPreferences encrypting the fields.
yes starting 2 or more asynctasks simultaneously may cause issues on some devices. i had experienced this issue few months back. i could not predict when the 2nd asyncTask would fail to run. The issue was intermittent may caused by usage of memory as i was executing ndk code in asynctask. but i remember well that it depended on memory of device.
Similar question had been asked before. I would post the link for the similar question.
AsyncTask.executeOnExecutor() before API Level 11
Some users suggest go for Service. My advice is don't go for that path yet. Using service is much more complicated. Even you are using service, you still have to deal with threading, as
Note that services, like other application objects, run in the main
thread of their hosting process. This means that, if your service is
going to do any CPU intensive (such as MP3 playback) or blocking (such
as networking) operations, it should spawn its own thread in which to
do that work....
If we can solve a problem in elegant way, don't go for the complicated way.
I would suggest that, try one of the APIs in java.util.concurrent as suggested in below
AsyncTask is designed to be a helper class around Thread and Handler
and does not constitute a generic threading framework. AsyncTasks
should ideally be used for short operations (a few seconds at the
most.) If you need to keep threads running for long periods of time,
it is highly recommended you use the various APIs provided by the
java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and
FutureTask.
I can't give you any code example so far, as I do not know how you design your session managing mechanism.
If you think your long running session managing task shouldn't bind to the life cycle of your main application life cycle, then only you might want to consider Service. However, bear in mind that, communication among your main application and Service is much more cumbersome and complicated.
For more details, please refer to http://developer.android.com/guide/components/services.html, under section Should you use a service or a thread?

Performance comparison: AsyncTasks vs Threads

In my app, I have to call a method which does some heavy work (I can feel device lagging). To avoid this I created an AsyncTask and it works perfectly fine.
I implemented the same thing using a Thread and here, too, it does not give any hiccup and works fine.
Now my question is which one better performance-wise - AsyncTask or Thread.
I know AsyncTask uses a threadpool to perform background tasks but in my case it will be called only once. So I don't think it will create any problems.
Can someone throw some light on it. Which one should I use for better performance?
Note: Both are being called in my Activity e.g. from UI the thread.
Can someone throw some light on it. Which one should I use for better
performance?
I think if you imagine case when you start once native Thread and AsyncTask i think that performance won't differ.
Usually native threads are used in the case if you don't want to inform potential USER with relevant information about progress in some task via UI. Here, native threads fail because they are not synchronized with UI thread and you cannot perform manipulating with UI from them.
On the other hand, AsyncTask combines background work with UI work and offers methods which are synchronized with UI and allow performing UI updates whenever you want via invoking proper methods of its lifecycle.
Generally if some task lasts more than 5 seconds you should inform USER that
"something working on the background, please wait until it will be finished"
For sure, this can be reached with both in different ways but this strongly depends on character of your task - if you need to show progress of task(how much MB is already downloaded, copying number of files and show name of each in progress dialog etc.) or you don't(creating some big data structure in "silent" only with start and end message for instance).
So and at the end of my asnwer:
Which one should I use for better performance?
Completely right answer i think you cannot get because each developer has different experiences, different coding style. How i mentioned, their performance not differ. I think that it's same(if you will read 50 MB file, it won't be faster read neither native thread nor AsyncTask). It depends again on character of task and your personal choice.
Update:
For tasks that can last much longer periods of time, you can try to think also about API tools provided by java.util.concurrent package(ThreadPoolExecutor, FutureTask etc.)
Async tasks are also threads. But they have some utility methods that make it very easy to small background tasks and get back to the UI to make changes to it. The performance would depend on your specific use case. Making absolute statements as to which one is always better would be simplistic and meaningless.
Note that the main advantage of Async tasks over threads is that Async tasks provide helper methods such as onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute() which make it very easy to perform short background tasks while also interacting with the UI (such as updating a progress bar). These kinds of methods are not available in generic Threads. Basically, Async tasks are threads with UI interaction component built in. Yes, you can use workarounds to try and update the UI from regular threads as well but Async tasks have been specifically built for this purpose and you don't have to deal with Context leaks and so on if you follow it's abstractions.
Async tasks are created to make developers' lives easier.
To sum up:
Async tasks are also threads
Async tasks make it easy to interact with UI while doing short background tasks
Neither is inherently more efficient. It depends on what you want to do.
Good rule of thumb: Use Async tasks if you need to get back to/update the UI after you are done with your background task. Use a regular thread if you don't.
The most common use of Thread are short-term tasks because they need a lot of power and tend to drain the battery and heat the phone up.
And the common use of AsyncTasks are lengthy tasks because of the same battery drain.
But a Thread is far more powerfull, because an AsyncTasks internally uses a Thread itself, but you don't have to configure that much.
ASYNC TASK and Thread do the same thing,
The difference is that you have more control on bare thread and you can benefit from the power of CPU in terms of complex implementation, the velocity of performance depends on your approach on how you implement the threading.
Depending on this article I can say that asynchronous multithreading is the fastest way to perform complex tasks.
https://blog.devgenius.io/multi-threading-vs-asynchronous-programming-what-is-the-difference-3ebfe1179a5
Regarding showing updates to user on UI thread, you can do that by posting on UI from the background thread (check UIhandler and View.Post)

Understanding when and why to use different Android threads

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)

Categories

Resources