Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android asynctask with threading

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 ?

like image 690
user1254554 Avatar asked Dec 07 '22 15:12

user1254554


2 Answers

AsyncTask automatically creates a new Thread for you, so everything you do in doInBackground() is on another thread.
What you are doing is this:

  1. AsyncTask creates a new Thread and runs doInBackground().
  2. a new Thread (t) is created from the AsyncTask-Thread.
  3. doInBackground() is completed, as all it does is create the Thread t and thus jumps to onPostExecute().
  4. Thread t would still be running in the background (however, you do not call 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);
    } 
}
like image 112
Jave Avatar answered Dec 09 '22 04:12

Jave


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();
}
like image 20
Vladimir Avatar answered Dec 09 '22 03:12

Vladimir