Search code examples
javaandroidmultithreadingrunnableheavy-computation

Taking heavy computation off the Android UI Thread


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?


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();