Question

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
}
Was it helpful?

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.
}

}

OTHER TIPS

Creating another thread won't help you if you still have to block and wait for the loop to complete the search. The problem really is what is happening in the "do stuff" loop, you just need to optimize that to solve the issue.

use asyntask and in asyntask's doInBackground , do your thread work and in asyntask's onPostExecute call your repositionMethod.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top