I know that AsyncTask are not preferred for long process. Their main objective is to take the load off from UI thread and do stuff in background. Later on completion update the respective UI thread.
I am aware of the memory leaks i.e when UI needs to be updated after doInBackground is done and there's a possibility that the activity is destroyed.
My question is can I use AsyncTask just like a simple Thread?
What happens to AsyncTask if Activity or Application dies, which started it?
Requirments
I dont need to update any UI.
I dont want my task to be associated with Activity(which starts it).
First Question :
Yes you can.Its totally depends on your logic.
Second Question :
The thread will be in the background though the application is killed by the user or by the system.
To resolve the second scenario use the following technique
Just make sure that you are finishing your AsyncTask before application or Activity closes
AsyncTask yourAsyncTask
#Override
public void onDestroy(){
//you may call the cancel() method but if it is not handled in doInBackground() method
if(yourAsyncTask!=null)
if (yourAsyncTask != null && yourAsyncTask.getStatus() != AsyncTask.Status.FINISHED)
yourAsyncTask.cancel(true);
super.onDestroy();
}
If you only need the 'doInBackground' just use a normal thread.
new Thread("threadName", new Runnable(){ #Override run(){ } }).start();
The whole reason to use an AsyncTask is to have the facilities of preExecute and postExecute, so you don't need to mess with handlers.
It remain started in background even the application is killed or crash.
First, a general note, as stated by the Android Docs:
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.
To answer your questions:
Yes - you can use Async task as if it were just a background thread - an Async task is merely a wrapper of Thread and Handler that allows the thread to seamlessly communicate with the UI thread. Warning! If you plan to update the UI thread, or otherwise reference an activity or fragment in the callbacks that reference the UI thread (i.e. onProgressUpdated and/or onPostExecute) you should explicitly check that the activity or fragment is still in a state from which it can be referenced and used. For example - here's the right and wrong way to do it when launching an AsyncTask from a fragment:
Create your task with a ref to the activity so you can do something when it's done:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
Fragment mFragment;
public DownloadFilesTask(Fragment fragment){
mFragment = fragment;
}
WRONG:
protected void onPostExecute(Long result) {
// if the fragment has been detached, this will crash
mFragment.getView().findView...
}
RIGHT:
protected void onPostExecute(Long result) {
if (mFragment !=null && mFragment.isResumed())
... do something on the UI thread ...
}
}
If the Activity dies while an AsyncTask is executed, it will continue to run. Using the techniques listed above, you can avoid crashes by checking the lifecycle of the context that started the task.
Finally, if you have a very long-running operation that does not require the UI thread at all, you should look into using a Service. Here's a blurb:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use
My question is can I use AsyncTask just like a simple Thread?
Yes AsyncTask is android background thread , the task will be done in the background .
AsyncTask automatically creates a new Thread for you, so everything you do in doInBackground() is on another thread.
What happens to AsyncTask if Activity or Application dies, which
started it?
The AsyncTask is related to application , if application destroy or finish then all related AsyncTask of that application will be terminated .
Related
Android Asynctask Generally Understanding Questions.
If I want to make Asynctask SyncTask, how do I do that?
AsyncTask A = new AsyncTask();
AsyncTask B = new AsyncTask();
A.execute();
B.execute();
If I want A to finish before B starts how should I do that?
If I close an Activity, does the AsyncTask call on that activity gets destroy?
If I close the whole application, does the AsyncTask call on that application gets destroy?
call b.execute() in onPostExecute() of A
AsyncTask is an abstract class so you must extend it in order to add your app specific functionality to it. You implement the doInBackground() method to do what ever work is required. The AsyncTask documentation explains it in detail. I will give a brief answer to each of your question.
If I want to make Asynctask SyncTask, how do I do that?
You have the right idea with creating the async task, however as I mentioned before you have to subclass the async task to actually do some work.
Here is an example (note that the Void types do have meaning however the documentation covers them in great detail)
public class MyTask extends AsyncTask<Void, Void, Void>
{
//This method will run on the back ground thread
#Override
protected Void doInBackground(Void... params)
{
// All the heavy work should be done here e.g.
// loading from network, database etc.
return null;
}
}
Then in your activity you would create and run this task as follows :
MyTask myTask = new MyTask();
myTask.execute()
If I want A to finish before B starts how should I do that?
As the documentation states:
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with DONUT, this was changed to a pool of
threads allowing multiple tasks to operate in parallel. Starting with
HONEYCOMB, tasks are executed on a single thread to avoid common
application errors caused by parallel execution.
Which means if you are using honeycomb or later async tasks will run on a single thread. So normally A should get executed before B if you execute in that order. But I would do something like this: Launch A, then when onPostExecute() of A gets called, you know that A is done, you can start your task B from this method to be sure that A finishes before B.
If I close an Activity, does the AsyncTask call on that activity gets
destroy?
The short answer to this question is No. The async task will continue to run even if the activity has called on destroy. However if the async task is tied to the activity life cycle you need to make sure you end the task when the activity dies or you will run into problems.
If I close the whole application, does the AsyncTask call on that
application gets destroy?
I am not 100% sure about this one. I believe the behavior is unspecified since now its up to Android to collect resources. It may decide to kill the task right away if its low on resources or it may not. However you should avoid this design. If you need to run something after your application has closed, then look at the Service class.
Take a look at http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.VNtB1LDF_38 it may help you.
I have a activity with a Listview and a adapter attached to it. I have a class which syncs data and hold it. (I think we should not care about from where data is coming) and it runs on a different thread. Now I want to know the clean way to update adapter but We should not call any function of activity from that class as it runs on different thread.
One way I know is to create handler in activity and pass it to other class and use it from there. But I want to know if activity is in background then activity's function can be called by UI thread or only when activity come in foreground.
I do not want to miss any update and want to update activity when it is in foreground.
If you want to update your listView from another class you can have a few ways to do that.
Send broadcastIntent from your worker class and add BroadcastReceiver to your activity and when you receive the right message, update your listview.
Second way is to create private or public class in your Activity which extends AsyncTask and in your doInBackground() do your work and in onPostExecute(result) update your listview.
Third way which I can imagine, but I don't think it's the best way create a static method is your activity which you can use from any other class for updatiogn your UI.
The best thing which you can use here at least in my opinion is AsyncTask.
this code will do what you want:
runOnUiThread(new Runnable() {
#Override
public void run() {
//your actions
}
});
We should not call any function of activity from that class as it runs on different thread.
That's wrong. (in java an object is not running in a thread. What you can say is that a method is running in the thread from which the method was called)
In Androïd (and in most UI frameworks) the rule is this:
You can only call a method updating UI from the UI thread.
If you have some code running on a thread (not the ui thread) and if that code need to update the UI : you can use the Handler of the UI-thread to post UI update code to the UI-thread. If the activity is not in the foreground when you post something to update it's UI : nevermind! the code you just post will be executed at some point in the future.
You should use AsyncTask, take a look at http://developer.android.com/reference/android/os/AsyncTask.html
I am confused with respect to design of my app. I need to continuously poll a server to get new data from it. I am confused whether Async Task running at fixed interval or Service running is background is better option. The thread will run only when the app is running
You have already some answers to your question, but I think it worths a summary ...
What you need
When you want to run a peice of code that takes some time to complete you should always run it in a separate thread from the UI thread.
You can achieve that in 2 ways:
Using Thread:
This is the simplest one, if you don't need a lot of communication from the new thread to the UI thread. If you need the communication, you will probably have to use a Handler to do it.
Using AsyncTask:
Also runs in a separate thread and already implements some communications channels with the UI thread. So this one is preferable if you need this communication back to the UI.
What you don't need
Service
This serves mainly to keep some code running even after you exit the main application, and it will run in the UI thread unless you spawn a new thread using the options described above. You said that your thread are suposed to terminate when you exit application, so this is not what you need.
IntentService
This can be activated by an external event (i.e. BroadcastReceiver) that can start a piece of code defined by you, even if your application is not running. Once again, based on your requirements, this is not what you are looking for.
Regards.
an Android Service is not in a background thread.
Therefore you should have a Service running that will start an ASyncTask each time you want to poll.
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. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.
Service should not be compared to AsyncTask. I guess you most likely meant IntentService here - and this is slightly different thing than Service, despite the common name.
As for periodical fetching, I'd stick with recurrent alarm (using AlarmManager) and (most likely) use IntentService to do the fetching.
Here you got with AsyncTask fundamentals and some tutorials
And here you got with IntentService fundamentals and tutorials
Note, that IntentService jobs are queued by design, while AsyncTasks can run fully paralel. However be aware of regression related to AsyncTask handling in newer APIs. Not a big deal as workaround is just a few more code lines, however it's worth knowing that.
EDIT
There's misunderstanding floating among many concerning AsyncTask lifecycle being bond to Activity's life cycle. This is WRONG. AsyncTask is independent from an Activity. Finishing Activity does not do anything to any AsyncTasks, unless you are cleaning them up from onDestroy() by your code. Yet, if an activity's process is being killed while it is in the background, then AsyncTask will also be killed as well, as part of the entire process being killed
If you want to "continuously poll", an asyncTask won't do. The task stops when your app gets stopped by Android. A Service by itself won't do either, as Blundell already pointed out. A Service runs in the main thread, and you don't want to do polling in the main thread. There's two ways of doing it: you create a Service that spawns its own thread to do the stuff you want it to do, or you let it schedule polls that are executed in an AsyncTask or in a separate thread. I try not to have polling in my app, but if you have to, creating a special thread in your service that does the polling seems best to me.
Depending on what your app does and what the polling is about, you can give the separate thread a lower priority, so it doesn't get in the way of other processing.
The thread will run only when the app is running
Then AsyncTask will be the simplest solution. Send data periodically to app thread using publishProgress() from background thread. Set desired interval using Thread.sleep() in doInBackground(). Also, make sure you start a new task in onResume() method of Activity, and end this task in onPause() method of Activity.
Example:
public class MyActivity extends Activity {
private AsyncTask<Void,String,Void> mAsyncTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
mAsyncTask = new MyTask();
mAsyncTask.execute();
}
#Override
protected void onPause() {
super.onPause();
if(mAsyncTask != null){
mAsyncTask.cancel(true);
}
}
private void onServerResponse(String response){
Toast.makeText(this, "Got response !", Toast.LENGTH_SHORT).show();
}
private final class MyTask extends AsyncTask<Void,String,Void>{
#Override
protected Void doInBackground(Void... voids) {
while (!isCancelled()){
String response = "";
//server query code here
publishProgress(response);
Log.i("TEST", "Response received");
//sleep for 5 sec, exit if interrupted ,likely due to cancel(true) called
try{
Thread.sleep(5000);
}catch (InterruptedException e){
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if(values.length > 0){
onServerResponse(values[0]);
}
}
}
}
I'm getting an Unable to destroy activity xxx: android.database.sqlite.SQLiteException: unable to close due to unfinalised statements error while my activity is being destroyed. I presume this is because I'm performing database operations from within AsyncTasks and they are somehow being killed before completion.
How can I ensure that my AsyncTasks actually complete before the activity is stopped? Incidentally, I thought that an AsyncTask can't be explicitly killed without the AsyncTask agreeing to do so by checking.
It may be relevant that this error is occurring during Robotium integration testing. I suspect it's happening after the test is completed and the test calls Robotium.finishOpenedActivities(). My guess is that somehow the AsyncTask is being forcefully killed mid-execution if this is possible (though I don't explcitly support cancellation in my AsyncTask implementation). Additionally, I use OrmLite for my database access.
It looks like if I override the onPause() event in my activity, and from within the overridden onPause(), I call cancel(false) on the AsyncTasks, then the activity is not destroyed until the AsyncTasks are completed.
You can check AsyncTask.getStatus() against AsyncTask.Status.RUNNING at any time.
Perhaps you need to make your activity and your AsyncTask aware of each other as was asked in this question Is AsyncTask really conceptually flawed or am I just missing something? and the answer by #hackbod explains exactly how
There are several things you can do here:
Override these methods and see determine exactly what state the object is in when it is closed. It seems that onPostExecute is going to get called when the AsyncTask is done. If it has not been called its too early.
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
}
You can also execute as follows:
// with THREAD_POOL_EXECUTOR.
executeOnExecutor(java.util.concurrent.Executor, Object[])
Make sure you are following the first two rules in the documentation: Are you following 1 and 2?
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.)
I want to ensure that I don't slow down my app's startup time and need to start a background task that's unrelated to user input--for instance, filling a cache.
If I start an AsyncTask from my onCreate method, when will the doInBackground method actually begin to execute? (Assume a single core device)
Is it possible that Android could schedule it before onCreate/onResume has completed, or is it smart enough to recognize that the background thread shouldn't run until the UI thread is completely finished?
If you look at AsyncTask source code you will see that it is just using ThreadPoolExecutor or serial executor for running tasks. Default internal behavior depends on Android version (from AsyncTask docs):
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
But anyway doInBackground execution is not connected with Activity lifecycle so AsyncTask may be executed at almost any time. This depends only on how many tasks you have already started, on default Executor which is used by AsyncTask and on thread scheduler.
I usually use AsyncTasks in onCreate() like this:
private MySuperSpecialTask mySuperSpecialTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(...);
// [...]
mySuperSpecialTask = new MySuperSpecialTask();
mySuperSpecialTask.execute();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mySuperSpecialTask != null) {
mySuperSpecialTask.cancel(true);
}
}
This makes sure that everything is initialized before the task gets started.
actually strictly speaking there is no execution order of your UI code and starting the asynctask I found out. Normally one does not experience this, however, if your UI thread takes longer for some reason, eg waiting for external input etc, the asynctask might have gotten started BEFORE UI code has finished.
Writing UI code is just a request to the Android system and this waits in the execution loop. So if asynctask starts before that because there are enough ressources (or as mentioned UI thread is delayed for whatever reason) there is no execution order guarantee.
One easy way to enforce this is - in case you don't mind and you can be sure that it is suffiencient - delay the starting of the asynctask with ScheduledExecutorService or a "cleaner" way would be to implement some kind of gate keeper that waits for a flag to be set to true and then start the asynctask. Or you may even have a while-loop at the beginning of your asynctask that waits for the flag to be set to true, like in many communication situations with external devices.
The flag would be set to true AFTER you can be (normally) sure that your UI has finished.