Asynctask doInBackgound () does not work if asynthesis is already running

When a user logs into my application. I run asynctask to save a user session. And this async task runs unlimitedly until the user logs out. My problem is that when I try to run another asynctasks , their doInBackground() method never executes.

I read somewhere that if an async task is already running, we cannot start a new async task . I can confirm this because when I deleted the user asynchronous session task, it worked correctly. Is there a workaround?

PS: I already used the executeOnExecutor() method. but it did not help.

+6
source share
7 answers

For potentially lengthy operations, I suggest using 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 learn more about Service , you can refer to this

Service: Android Developers

Service: Vogella

To learn more about asynctask vs Service , you can link to this

Android: AsyncTask vs Service

When to use the Service or AsyncTask or Handler?

+5
source

I read somewhere that if an async task is already running, we cannot start a new async task.

Yes, it is a fact that you cannot run more than 5 (five) AsyncTask simultaneously under API 11, but for more yes you can use executeOnExecutor .

AsyncTask uses a thread pool template to run stuff from doInBackground() . Initially, the problem (in earlier versions of Android OS) the pool size was only 1, which means the lack of parallel computing for the AsyncTasks group. But later they fixed it and now size 5, so no more than 5 AsyncTasks can run simultaneously.

I figured out some threading rules , and I found one basic rule below,

 The task can be executed only once (an exception will be thrown if a second execution is attempted.) 

What is the definition of AsyncTask ?

AsyncTask allows you to correctly and easily use the user interface thread. This class allows you to perform background operations and publish results to a user interface thread without the need to manipulate threads and / or handlers.

How and where to use it?

AsyncTask is intended for a helper class around Thread and Handler and is not a common thread structure. AsyncTasks should ideally be used for short operations (maximum of a few seconds). If you need to maintain threads for extended periods of time, it is highly recommended that you use them.

Why can't you use multiple AsyncTask at the same time?

There are several streaming rules that must be followed for this class to function properly:

  • The AsyncTask class must be loaded into the user interface thread. This is done automatically with JELLY_BEAN.
  • An instance of the task must be created in the user interface thread.
  • execute(Params...) must be called in the user interface thread.
  • Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
  • A task can be executed only once (when trying to execute a second execution, an exception will be thrown).

  • Running multiple asynchronous tasks at the same time is impossible?

  • Verify AsyncTasks parallel extraction pattern

Try performer

You have to go with an Executor that will mutate your parallel thread.

 Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); ... 
+4
source

Like some others, I object to the premise of the question.

The main problem is that you are using AsyncTask to perform a task that goes beyond its scope. Others also noted this. Those who offer solutions that can reduce your problem through low-level streams (even java.util.Concurrent are low-level, so Scala uses Akka actors as an abstraction), Service , etc. Pretty smart, but they are a cure for the symptom, not a cure for the disease.

As for what you should be doing, you are not the first to want to maintain a user session in an Android app. This is a resolved issue. A common thread (no pun SharedPreferences ) in these decisions is to use SharedPreferences . Here is a simple example of this. This user combines SharedPreferences with OAuth to make something more complex.

In software development, it often solves problems, preventing them in the first place. I think you can solve the problem of running AsyncTask without running AsyncTask s simultaneously. User session management just doesn't match AsyncTask .

+3
source

If you are developing API 11 or higher, you can use AsyncTask.executeOnExecutor() , allowing you to run multiple AsyncTasks at once.

http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor (java.util.concurrent.Executor, Params ...)

+2
source

I will share with you what we do in our application.

To save a user session (we use OAuth with access / update tokens), we create Singleton in our extended class . Why do we declare this Singleton inside the MainApplication class? (This is the name of our class), because your Singleton life will be tied to the Activity that created it , so if your application runs on low memory, and the garbage collector collects your paused actions, it will free the Singleton instance because it is associated with by this action.

Creating it inside your Application class will allow it to live inside your RAM while the user continues to use your application.

Then, to save this cross-application for the session, we save the credentials inside SharedPreferences, encrypting the fields.

+2
source

yes, starting with two or more asynchronous tasks at the same time, problems can occur on some devices. I survived this question a few months ago. I could not predict when the second asynchronous program could not execute. The problem was intermittent caused by memory usage as I was executing ndk code in asynctask. but I remember well that it depended on the device’s memory.

+1
source

A similar question was asked before. I would post a link to a similar question.

AsyncTask.executeOnExecutor () up to API level 11

Some users suggest switching to Service . My advice is not going this way yet. Using the service is much more complicated. Even if you use the service, you still have to deal with threads, as

Note that services, such as other application objects, are started primarily by the flow of their hosting process. This means that if your service (for example, playing in MP3 format) or blocking (for example, as network), it must create its own stream, do this work ....

If we can solve the problem in an elegant way, don’t go in a difficult way.

I would suggest that try one of the APIs in java.util.concurrent as shown below

AsyncTask is intended for a helper class around Thread and Handler and does not represent a common thread structure. AsyncTasks should ideally be used for short operations (a few seconds for most.) If you need to maintain threads for a long time, it is highly recommended that you use the various APIs provided by the java.util.concurrent pacakge, such as Contractor, ThreadPoolExecutor and FutureTask.

I can’t provide you with any sample code yet, since I don’t know how you create your session management mechanism.

If you think that your long-term session management task should not be tied to the life cycle of the life cycle of your main application, then you can consider Service . However, keep in mind that the connection between your main application and Service is much more cumbersome and complex.

For more information, see http://developer.android.com/guide/components/services.html in the section If you use a service or stream?

+1
source

All Articles