I'm creating an application which communicates with a web service.
I have a method heartBeat I would like to call asynchronous every 5secs or so. My problem is not how to do this asynchronous. But how I keep the job done. I use a inner class which inherit from AsyncTask. My question is how can I start this thread every 5sec?
I have tried something like from doInBackground()
while (true) {
...
Thread.sleep(5000);
}
but I also need the return statement, to tell the UI thread whatever the web service is available or not.
You can use publishProgress() from within doInBackgroound() and then do UI stuff in onProgressUpdate()
Related
I am working on app that updates data for every 8 secs and the update was done using Async task. I am using loops to achieve this condition
while(const_val > update_val) {
new Asynctask().execute();
Thread.sleep(8000);
}
const_val will be constant and will be not be changed by any other methods.lets say this value will be 5.update_val will be updated and decremented when Asynctask is called and let's the value will be 10. So , the while loop executes until the condition is true and asynctask ,sleep are called .
When I use above while loop in a general method then UI gets locked and if I use the same loop in another asynctask there was an error saying "Only original thread that created a view hierarchy can touch its view "
You need to change your code to start the AsyncTask and have it provide an update via its onPostExecute() method. By calling Thread.sleep() you are sleeping the main thread (or UI thread) of your app, which is not good. You do not ever want to block the main thread. This article may help you better understand AsyncTask and threading in Android: http://po.st/Cei3m2
I don't think you should use a surrounding loop. Look at this example:
http://javatechig.com/android/progress-notification-in-android-example
the AsyncTask is a private inner class
the onPostExecute updates the UI with a message/cancels the load bar
This way you don't have to loop and the onCreate() can return instantly.
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().
Should we start async task from within onHandleIntent() method of IntentService? I read that onHandleIntent() runs in worker thread so will it be safe to start asyncTask from there??
IntentServices already are background-processes; there's no need to start an AsyncTask from there. Also, starting an AsyncTask is 'safe' from anywhere; it's a helper class that helps you multithread. Just make sure you don't manipulate Views in the doInBackground()-method of your AsyncTask if you use it in your Activity.
If you need to spawn multiple threads inside your IntentService, just use:
new Thread(Runnable r).start();
See an example at How to run a Runnable thread in Android?
If you need to call some kind of callback, use Handler. For an example, see http://www.vogella.com/articles/AndroidPerformance/article.html#handler
AsyncTask class is used to provide a mechanism to do achieve multithreading, so your event thread wont get hanged, but as you are using service, you should not use, AsyncTask in the Service, instead you can use, threads, if some long running task is to executed, in the Service.
If you really need to use a AsyncTask inside an IntentService, you can create a method in your AsyncTask that calls de doInBackGround and the onPostExecute. Something like this:
void executeFlowOnBackground(Params params) {
onPostExecute(doInBackground(params));
}
In my case I did this because all App request were made by a class that extended the AsyncTask, and because of the implementation was difficulty to refactor the code.
Why can an AsyncTask perform only one job? For example,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
But a Handler can continously perform more than one task:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Is an AasyncTask object for a one-time job only? If I don't want to create multiple object for similar task, should I choose Handler?
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
Async task enables you to implement MultiThreading without get Hands dirty into threads. Async Task provides some methods which need to be defined to get your code works. in onPreExecute you can define code, which need to be executed before background processing starts. doInBackground have code which needs to be executed in background, in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread, onPostExecute() method handles results returned by doInBackground method.
So, you dont need to call execute method on AsyncTask multiple TImes, instead you can invoke publishProgress.
Because that is how the class was designed. The idea is: do something with UI (show progress dialog, etc.), do work on background thread and return results, update UI. The Handler is fundamentally different: it lets you post messages, but it does not create a background thread for you. If you don't like how AsyncTask works, build something similar by using threads/executors and handlers.
I am using AsyncTask to upload data to UI. i wrote the code to download data from server in a separate method and i am calling that method from doinBackground. It will give error because UI methods can't access from doInBackground.but, i want to access . any alternative process is there to access the UI method from doinBackground.?
any alternative process is there to access the UI method from doinBackground.?
Call publishProgress() in doInBackground(). Put your UI-updating logic in onProgressUpdate() of your AsyncTask. onProgressUpdate() will be called on the main application thread (a.k.a., UI thread) after you call publishProgress(). Here is a sample project demonstrating this.
Call runOnUiThread(Runnable action)
more here
Use doInBackground() just for tasks that :
Take some time
Are not UI related
Then you can implement AsyncTask.onPostExecute() to run code to handle those results on main UI thread from AsyncTask
From JavaDoc for AsyncTask.onPostExecute():
"Runs on the UI thread after doInBackground. ... "
As the others have pointed out, you can use runOnUiThread. But, it seems a little odd that you would want to do that in your doInBackground. If you are wanting to indicate progress to the user you would want to handle that in AsyncTask.onProgressUpdate and call publishProgress in your doInBackground.
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
-Dan