I know there is alot of stuff AsyncTask and i've been exploring for quite some time but still havent found soultion. I have to upload images on FTP server in serialized manner. I know that on and after API 11, AsyncTask executes sequentially by default. But, NOT EXACTLY SEQUENTIAL ... So far my observations are : only DoInBackgorund() method executes sequentially , so if you have N asynctasks being called for execution , their OnPreExecute() are called independent of the execution of anyother Asynctask being executed. What i want is complete sequential execution Like this :
ASYNCTASK 1 :
OnPreExecute();
DoInBackgorund();
OnPostExecute();
Followed By :
ASYNCTASK 2 :
OnPreExecute();
DoInBackgorund();
OnPostExecute();
Followed By :
ASYNCTASK 2 :
OnPreExecute();
DoInBackgorund();
OnPostExecute();
... and so on.
Please provide me with some idea, tweak or concept to achieve complete sequential execution of async threads. Dummy code will be appreciated. Thanks in advance.
EDIT : image uploading mechanism is perfectly fine and images are being uploaded. i'am creating instances of uploadTask (my asyncTask for uploading image) and executing them in loop. Only problem is ; i've to update UI in OnPreExecute() of each thread ( to show number of image being uploaded , in TextView). This is my problem since OnPreExecute()are not being executed sequentially.
Simplest option: only have one AsyncTask, where you process all the work in a single doInBackground(), using publishProgress() and onProgressUpdate() to publish per-download results, if needed. I do not know why you think having N non-parallel AsyncTask instances is a good idea.
Or: don't use AsyncTask at all. Use your own ThreadPoolExecutor, so you have complete control over the characteristics of your jobs. Use an event bus (greenrobot's EventBus, Otto, LocalBroadcastManager, etc.) to publish the results on the UI thread.
Or: From onPostExecute() of the first AsyncTask, start the next AsyncTask in your chain.
Implement a interface callback on the OnPostExecute()
eg.
//activity
MyActivity extends Activity implements MyInterface
{
#Override
public void Task1Complete()
{
new StartTask2(getActivity, MyActivity.this).execute();
}
//Interface
public interface MyInterface
{
void Task1Complete()
}
//AsyncTask1
public class task1 extends AsyncTask<Void,Void,Void>
{
Context ctx;
MyInterface myInterface;
public task1(Context _ctx, MyInterface _myInterface)
{
this.ctx = _ctx;
this.myInterface = _myInterface;
}
doinbackground{}
onpostexecute()
{
myInterface.Task1Complete();
}
Related
I am new to android, i have built an application where lot of web services are used. i am using async task doInBackground() method to make a call to webservices.
my asyntask class is public and it is written in a separate file.
i am not using onPostExecute to carry out postwebservice operations,
instead i am creating a string and returning back.
then in my activity class i am examining the string and packing the data using a java bean.
since Async task runs in an asynchronus way is it correct to rely on what doInBackground method returns. or is it must to perform my post webservice operations in onPostExecute only.
please guide me with the correct way of doing things for my project. Thanks.
Create an Interface and callback method for accessing AsyncTask class.
accessActivity or Context to ur AsyncTask using Constructor of that AsyncTask
In onPostExecute send the result to ur Activity using the
callback method
Tutorials
1.http://samir-mangroliya.blogspot.in/p/android-seperate-asynctask-class.html
2.http://www.androidsnippets.com/asyntask-in-android
3.http://www.brighthub.com/mobile/google-android/articles/82805.aspx
You should do all the post webservice work in onPostExecute, because this method is executed in the main thread (UI) an therefore you can update your UI.
Take a look at http://developer.android.com/reference/android/os/AsyncTask.html
A basic example (Taken from the docs)
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
// Here you call your webservice and return the result
return totalSize;
}
protected void onPostExecute(Long result) {
// The result from doinbackground is passed as an argument
// here, so you update your UI from this method.
}
}
As kaushik You can also reuse the Asyntask with a defined callback, check this questions:
public AsyncTask to be called from several classes
Common class for AsyncTask in Android?
I have a class AsycnIntegerCounter which extends AsyncTask, with doInBackground() and onPostExecute() overridden in the same.
From my main thread, I am able to create a runnable object and execute it using the
AsycnIntegerCounter's static execute method. AsycnIntegerCounter.execute(Runnable)
Can anyone help me in understanding what exactly happens when we execute a runnable using AsycnIntegerCounter (i.e) using AsycnTask object.
When this can be used ? and what is the advantage rather than running using a Thread object?
Code Sample:
AsycnIntegerCounter integerCounter1 = new AsycnIntegerCounter(next,0);
AsycnIntegerCounter.execute(new Runnable() {
#Override
public void run() {
int i = 100;
while(i<=105){
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
There are a couple of fundamental differences between
static void execute(Runnable)
and
AsyncTask execute(Params...)
Background task is defined in Runnable instead of implementing doInBackground
The Runnable-task is not using the internal thread communication mechanism of the AsyncTask. Hence, neither onPreExecute nor onPostExecute are called.
The latter is available on all platforms, whereas the first was added in API level 11.
The advantage of using execute(Runnable) is that the task can be executed on a worker thread of the internal thread pool, i.e. no new thread has to be created.
It's the same as execute() but it will run your Runnable in the background instead of running the doInBackround function. It can be useful when you have the same onPreExecute and onPostExecute but several runnables.
I guess the advantage over Thread.execute or an Executor is exactly calling onPreExecute and onPostExecute before and after.
#Alex makes a very good point. Suppose the you have a lot of methods, M1(), M2(), and so on that you wish to execute. Suppose that before executing any of them you need to execute method Before() and after you need to execute method After().
ie, the sequence of methods goes:
Before();
M1();
After();
Or
Before();
M2();
After();
By putting Before() in onPreExecute and After() in onPostExecute you can achieve that sequence. By making M a runnable, you can then achieve:
Before();
WhateverRunnableYouWant();
After();
With the Runnable in a background, non-UI, thread, as per your code.
As far as i figure it's like AsyncTask class but AsynchTask only runs once, but with this class it provides two things-:
It loops so it benefits, if you want a task to run multiple time
like checking for continuous data on a web service.
It fixed the running time of a task with Thread.sleep, so if a task finished
earlier it will fix the time of this task by Thread.wait().
Consider the scenario where I have get data from server and post it to UI in say list view , but this is an going activity ,it never stops.
taskA{ //fetches data over network
if(!update)
fetch();//network operation
}
taskB{//using this data UI is updated at runtime just like feed.
if(update)
show();//UI operation
}
taskA starts first after it completes taskB starts by that time A is sleeping and vice versa , goes , now the problems i am facing are:
both operations have to be in worker thread
both operations are going in cycle till activity is alive.
if handler is used to post UI operation to the main thread , taskB seems to stop.
Can anybody please suggest me a design to get this working?
AsyncTask is doing the job for you. You can make it as an inner class under your Activity main class.
http://developer.android.com/reference/android/os/AsyncTask.html
Example code
private class YourTask extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
// Fetch Data (Task A)
return "Result";
}
protected void onProgressUpdate(Integer... progress) {
// Show progress
}
protected void onPostExecute(String result) {
// Show UI after complete (Task B)
}
}
AsyncTask is what you're looking for. Check out this link for some sample code:
http://geekjamboree.wordpress.com/2011/11/22/asynctask-call-web-services-in-android/
You can also use IntentService you can check some sample code
An Android service is lightweight but more complex to setup.
AsyncTask is very easy but not recommended as it has many downsides and flaws.
You could also look into Loaders but it's not as easy as AsyncTasks.
I am developing an application for blind people. I have to work all the time with the TextToSpeech module, GPS and Network connection.
I need to do a query like this: Consult the GPS, do a JSON call and calling the TextToSpeech(TTS) module.
I am wondering the best way to deal with the different tasks which communicate with the UI main thread. I have seen so far:
Handler objects and AsyncTask class.
I have to launch each task sequentially, so I want to call the TTS after retrieving data from the network. So I have used "mHandler.post(Runnable)" and inside that runnable calling another one and so on.
However I have seen that is recommendable the use of the AsynTask class. But in this case I think I have to implement a different class for every task, whereas I don't know if those tasks will execute sequentially. Something like:
AsyntaskClass1 at1;
AsyntaskClass2 at2;
AsyntaskClass3 at3;
at1.execute();
at2.execute();
at3.execute();
Will that tasks execute in order? Cause the TTS module have to wait for the network task to finish...
Thanks for your help,
BR.David.
You could everything with a single AsyncTask class:
private class AsyncTask1 extends AsyncTask<Object, Void, Object> {
#Override
protected String doInBackground(Object... args) {
// Get a result from the GPS.
// Make a network call
// Communicate with the TTS
}
#Override
protected void onPostExecute(Object result) {
// Return a result to the main thread
// You are only allowed to touch the UI here
}
}
No they will be executed almost simultaneously... i.e. the second asynctask will not wait for first one to finish.
I suggest you to club all the tasks in one single AsyncTask and use publishprogress() to update the UI after each task finishes.
so you can start that AsyncTask after the network finishes and the UI will get updated sequentially
eg.
public Object doInBackground(Object... params){
//do task one's stuff
publishProgress(1);
// do task two's stuff
publishProgress(2)
//do task 3
publishProgress(3)
}
public void onProgressUpdate(Integer... int){
switch(int[0]){
case 1:
//ui update for task 1
case 2:
//ui update for task 3
case 3:
//ui update for task 3
}
The execution order is not guaranteed in your example. The UI thread would launch the 3 AsyncTasks. These three tasks would then execute concurrently.
If you want to execute the code in the tasks synchronously you have at least a couple of ways to acomplish it:
Combine the three tasks into one where you have ordered the work to be done sequentially i.e:
AsyncTaskCombined task = new AsyncTaskCombined();
task.execute();
private class AsyncTaskCombined extends AsyncTask<Void, Void, Void> {
protected Bitmap doInBackground(Void... urls) {
// Initialize classes that implement the work logic
Work1 work1;
Work2 work2;
Work3 work3;
// Do the work sequentially...
work1.doWork();
work2.doWork();
work3.doWork();
}
}
Or potentially you could have 3 different AsyncTask and then in the onPostExecute of the first task create and call the second AsyncTask and in the second AsyncTask's onPostExecute create and call the third and last AsyncTask. However that seems a bit contrieved to me...
// Emil H
In a scenario where I have a UI that will be updated from a separate thread (using AsyncTask), I can define the AsyncTask as an inner class of the activity, but this has two downsides I find problematic:
It makes the source files very large, reducing efficiency in managing the code
It makes it hard to reuse the thread class
What's a good solution? Use an inner class, but abstract everything it does to other classes? Pass a reference to the Activity to the AsyncTask? Always define the AsyncTask class as an inner class and just accept source files will be large?
First and foremost: when using an AsyncTask you must not do UI activity within doInBackground().
What you can do is - if you want to e.g. update status for a long running background job, is to publishProgress(values) from doInBackground().
The runtime will then for those values call your onProgressUpdate(values) callback, which runs in the UI thread and from where you can update the UI.
Have a look at e.g. https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/TweetListActivity.java#L336 to see an example.
The AsyncTask can be implemented in an own class file.
Quite a few examples I have seen just pass a Context into the constructor of the AsyncTask.
public class BackgroundStuff extends AsyncTask<Void, Void, Void> {
...
Context mContext;
...
BackgroundStuff(Context context){
super();
this.mContext = context;
}
...
}
I would be interested to hear if anyone else uses any other approaches.
I have a somewhat odd P.O.V with AsyncTasks because I generally prefer using normal Threads, but essentially the way I perform a background task and update a UI is create a Handler at the end of the onCreate() method, I'll then override the handleMessage(Message msg) method.
Then in my Thread, I'll pass the Handler in as a parameter, then when I wish to make an update I'll send a message from the thread to the Handler, now what this does is communicate from the new background thread onto the UI thread to process work on the UI.
Now I imagine AsyncTasks perform a similar task but removes the need to implement override the Handlers' handleMessage method.
It'd be interesting learning more about any advantages / disadvantages between these two approaches.