Search code examples
androidrunnableui-thread

Thread is stopping until the execution of a method is complete. (Android)


I'm trying to do an Android game using a Thread which repeats a loop for draw, move and others.

I have a problem with the execution of a method, which searches a value with a "do while" loop. When this method is executed, the thread does not continue until this process does not end.

What would be the best option for avoid this? Make another thread within that method? If you can give an example I'd really appreciate it.

Here's some pseudocode:

void mainLoop(){
    drawElements();
    moveElements();
    //...
    //...
    reposition();
}

void reposition(){
    // this stops my thread
    do{
        // do stuff
    }while(!end);

    // do stuff
}

Solution

  • As wqrahd suggested use AsyncTask. I assume mainLoop is a main UI thread.

    public class RepositionClass extends AsyncTask {

    private Context mContext;
    
    public RepositionClass(Context context) {
        mContext = context;
    }
    
    @Override
    protected void onPreExecute() { 
      // do UI related  here, this function will run in main thread context.
    }
    
    @Override
    protected Boolean doInBackground(String... params) {
       // call non-ui(computation intensive) part of reposition function here. 
       return true;
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
       // do UI related part of reposition function here.
    }
    

    }