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

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?

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.

What is the difference between thread and service in android , when downloading an image

What is the difference between thread and service in android,when downloading an image
There are lots of difference between Normal thread and a Service
Service: Due to android component it runs on UI thread but without any view shown to user. It runs in background with the same kind of property that an activity have, like you cannot run network operations (downloading image, calling web service) in service for that you have to use Thread which will run on worker thread other than UI thread.
Thread: Its an independent path of execution which can consist network operation, complex coding, huge amount of data transfer and accept. Thread is not related to android but in android it is used to perform different task. You can download an image on Thread but to show it on any UI part you have to update downloaded image on UI thread using runOnUIThread method
Please let me know if this explanation clears your doubt. If not let me know which part you did not understand and what exactly is your question.
With rare exceptions, you should never explicitly create a Thread. Threads are expensive and prone to programmer error. Use AsyncTask because it handles the complexity of thread safety and provides the optimization of thread pooling. Or better yet, if network activity is your reason for doing work outside the main thread, use one of the many network libraries that manages all of these concerns for you. Which approach is fastest is not something that can be answered generally, and should never even be a concern until you've tried the simple and clear solution and demonstrated that its performance is inadequate.
Regardless of how you make your network activity asynchronous, any network activity that is not started and completed (or cancelled) within the lifetime of a single Activity instance needs to be hosted in something else. If it only needs to survive across configuration changes, host it in a retained Fragment. If it needs to survive between different activities, host it in a Service. When choosing between these options, remember that your Activity may be destroyed any time it goes into the background or backstack.

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)

Multiple async tasks not executing properly

I am trying to start 6 async tasks at a time in onCreate() of the activity. But I noticed following:
a) If I stay on same activity all the async tasks' doInBackground() execute properly.
b) If I switch to some other activity, only 4 or 5 async tasks' doInBackground() executes. Last async task's doInBackground() never executes.
Can someone tell what I might be doing wrong. I am staring different asynctasks in a for loop. If I do this in onStart(), then all the async tasks are executed again if I switch to this activity. Please help.
Here is the sample code:
For(int i=0;i<7;i++){
webServiceTask= WebServiceTask.getInstance();
webServiceTask.execute("");
}
Maybe you should consider some of the following points:
Is the WebServiceTask retrieving any information that is worth persisting (i.e. not very volatile, with a high risk of the user requesting the same data over and over again): in that case you can offload your work to an (Intent)Service and communicate the result back to your app via a ResultReceiver, or a ContentProvider (just to name a few).
AsyncTasks are not guaranteed to run to completion if no Activity or Service is around to keep your app's process alive.
If it is ok that the WebServiceTasks run after eachother, then you can probably also change your code to use only one AsyncTask that sequentially performs those tasks. You can even consider implementing AsyncTask's progress reporting mechanism.
If the operations performed by the AsyncTask(s) have no meaning once the Activity is closed, be sure to .cancel() them in your onStop() or onPause() lifecycle methods.
Keep bullet 3 of Ed Rowland's answer in mind, which I also posted in my earlier comment to your question.
Happy coding!
You need a Service of some kind to keep your process alive after the user switches away. Once your activity loses focus, Android is free to shut down your process altogether. Or your Activity. Either will cause problems, particularly if you are using the context of an Activity that has been shut down.
The Right Thing to Do (tm) is to implement a Service, and pass the operations off to the service for execution.
There are any of a bunch of reasons why only four tasks are running concurrently. Off the top of my head:
HttpConnection pools connections to servers, and throttles the
maximum number of connetions to any given server to some reasonable
value. 4 sounds about right.
your target server is throttling the number of simultaneous connections.
Your thread pool isn't as large as you think it is. Starting an API 16 (I think) the default threadpool size is one thread! (!!) Rationale: apparently Android OS developers got fed up with Android app developers doing threading wrong. Is it possible your tasks are executing serially? That would more or less fit the symptoms you describe.
But that's kind of a separate issue.

Android AsyncTask for long running operations

Quoting the documentation for AsyncTask found here, it says:
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.
Now my question arises: why? The doInBackground() function runs off the UI thread so what harm is there by having a long running operation here?
It is a very good question, it takes time as an Android Programmer to fully understand the issue. Indeed AsyncTask have two main issues that are related :
They are poorly tied to the activity life cycle
They create memory leaks very easily.
Inside the RoboSpice Motivations app (available on Google Play) we answer that question in detail. It will give an in-depth view of AsyncTasks, Loaders, their features and drawbacks and also introduce you to an alternative solution for network requests : RoboSpice.
Network requests are a common requirement in Android and are by nature long running operations
.
Here is an excerpt from the app :
The AsyncTask and Activity life cycle
AsyncTasks don't follow Activity instances' life cycle. If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes.
And when it completes, the AsyncTask won't update the UI of the new Activity. Indeed it updates the former instance of the activity that
is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you
use, for instance, findViewById to retrieve a view inside the Activity.
Memory leak issue
It is very convenient to create AsyncTasks as inner classes of your Activities. As the AsyncTask will need to manipulate the views
of the Activity when the task is complete or in progress, using an inner class of the Activity seems convenient : inner classes can
access directly any field of the outer class.
Nevertheless, it means the inner class will hold an invisible reference on its outer class instance : the Activity.
On the long run, this produces a memory leak : if the AsyncTask lasts for long, it keeps the activity "alive"
whereas Android would like to get rid of it as it can no longer be displayed. The activity can't be garbage collected and that's a central
mechanism for Android to preserve resources on the device.
It is really a very very bad idea to use AsyncTasks for long running operations. Nevertheless, they are fine for short living ones such as updating a View after 1 or 2 seconds.
I encourage you to download the RoboSpice Motivations app, it really explains this in-depth and provides samples and demonstrations of the different ways to do some background operations.
why ?
Because AsyncTask, by default, uses a thread pool that you did not create. Never tie up resources from a pool that you did not create, as you do not know what that pool's requirements are. And never tie up resources from a pool that you did not create if the documentation for that pool tells you not to, as is the case here.
In particular, starting with Android 3.2, the thread pool used by AsyncTask by default (for apps with android:targetSdkVersion set to 13 or higher) has only one thread in it -- if you tie up this thread indefinitely, none of your other tasks will run.
Aysnc task are specialized threads that are still meant to be used with your apps GUI but whilst keeping resource-heavy tasks of the UI thread. So when stuff like updating lists, changing your views etc require you to do some fetch operations or update operations, you should use async tasks so that you can keep these operations off the UI thread but note that these operations are still connected to the UI somehow.
For longer-running tasks, which don't require UI updation, you can use services instead because they can live even without a UI.
So for short tasks, use async tasks because they can get killed by the OS after your spawning activity dies (usually will not die mid-operation but will complete its task). And for long and repetitive tasks, use services instead.
for more info, See threads:
AsyncTask for longer than a few seconds?
and
AsyncTask won't stop even when the activity has destroyed
The problem with AsyncTask is that if it is defined as non-static inner class of the activity, it will have a reference to activity. In the scenario where activity the container of async task finishes, but the background work in AsyncTask continues, the activity object will not be garbage collected as there is a reference to it, this causes the memory leak.
The solution to fix this is define async task as static inner class of activity and use weak reference to context.
But still, it is a good idea to use it for simple and quick background tasks. To develop app with clean code, it is better to use RxJava to run complex background tasks and updating UI with results from it.

Categories

Resources