Question

My Android app employs a particularly big computation which keeps crashing the system because it is on the UI thread in the Activity. I have little confidence in multithreading and so I want to get some tips on how to do it correctly. This is what I have

class ActivtyName extends Activity{
boolean threadcomplete = false;

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//stuff

Runnable newthread = new Runnable(){

            @Override
            public void run() {
                doBigComputation();
                threadcomplete=true;
            }

        };

        newthread.run();

        boolean b = true;
        while(b){
            if(threadcomplete){
                b=false;
                startTheApp();
            }
        }

}
}

Now, I am pretty sure what I have done is not "correct". (It seems to work though. The sistem doesn't crash). Basically, I'm not sure how the UI thread can be told that newthread has finished the computation without this boolean, threadcomplete. Is there a "correct" way to do this?

Was it helpful?

Solution

Just to expand a bit on Marek Sebera's comment, here's the framework on how you would accomplish that in an AsyncTask.

private class BigComputationTask extends AsyncTask<Void, Void, Void> {

  @Override
  protected void onPreExecute() {
    // Runs on UI thread
    Log.d(TAG, "About to start...");
  }

  @Override
  protected Void doInBackground(Void... params) {
    // Runs on the background thread
    doBigComputation();
  }

  @Override
  protected void onPostExecute(Void res) {
    // Runs on the UI thread
    Log.d(TAG, "Big computation finished");
    startTheApp();
  }

}

And to call it:

BigComputationTask t = new BigComputationTask();
t.execute();

OTHER TIPS

In addition to Marvin's answer, there's a good article on the Android developer site about precisely this.

That's not the correct way to start a thread. You need to do:

    Runnable newthread = new Runnable(){

        @Override
        public void run() {
            doBigComputation();
            threadcomplete=true;
        }

    };

    Thread t = new Thread(newthread);
    newthread.start();

    boolean b = true;
    while(b){
        if(threadcomplete){
            b=false;
            startTheApp();
        }
    }

When i want to use threads, I've almost a big while loop. I put a boolean condition who's always true, except when I want to stop it.

I use Thread (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html) and I reimplement the stop method because it's deprecated. So in my stop method I can put a false value to the loop variable.

To terminate the thread, I use t.stop(). So you can di that in your activity.

If you want to know when a Thead stops, you can use t.isAlive(). If the thread t is started, isAlive will return true.

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