Reputation: 203
I created an asynctask and in its doInBackground() method i started a thread like this:
private class myAsyntask extends Asynctask{
doInBackground(){
Thread t = new Thread(new Runnable(){
public void run()
{
while(someBoolean!=true){
Thread.currentThread.sleep(100);
}
}
});
}
onPostExecute(){
//do something related to that variable
}
}
problem I am facing is after 1st iteration of Thread.sleep()
, onPostExecute()
is called , instead I thought that asynctask will run this thread on background and when that boolean is true onPostexecute() is called.I am not able to understand why this happens ?
Upvotes: 4
Views: 11653
Reputation: 9743
First of all, in your code you don't even start thread t
, so all that happens in doInBackground
is creation of new thread and then moving on to onPostExecute()
.
Secondly, you don't even need separate thread, since doInBackground()
handles this for you, so you can just use something like
doInBackground(){
while(someBoolean!=true){
Thread.currentThread.sleep(100);
}
}
if you wish, however, to stick with separate thread, you can start thread and wait for it's completion by using .join(); like
doInBackground(){
Thread t = new Thread(new Runnable(){
public void run() {
while(someBoolean!=true){
Thread.currentThread.sleep(100);
}
}
});
t.start();
t.join();
}
Upvotes: 3
Reputation: 31846
AsyncTask automatically creates a new Thread for you, so everything you do in doInBackground()
is on another thread.
What you are doing is this:
doInBackground()
. t
) is created from the AsyncTask-Thread. doInBackground()
is completed, as all it does is create the Thread t and thus jumps to onPostExecute()
. start()
on t
, meaning that it is not started).Instead you want your doInBackground()
method to look something like this:
doInBackground(){
while(someBoolean!=true){
//Perform some repeating action.
Thread.sleep(100);
}
}
Upvotes: 11
Reputation: 20219
onPostExecute
can only be called when doInBackground
has return
-ed. In your code, the only possible way this can happen is sleep
throwing an Exception
(InterruptedException
??)
Upvotes: 1