Threading and Asynchronous Processing In Android OS - Part 1

Some tasks in application development require threading and asynchronous processing due to complexity of the task. For example networking, complex calculations, querying data over the network, parsing data, accessing remote database require threading. Unless Android Operating system decide that application is not responding and throw Application Not Responding (ANR) event.

There are three ways to manage complex and time consuming processes. They are,
  • By using AsynTask helper class.
  • By using standard Thread class.
  • Or using the Loader class.
AsyncTask Helper Class

Create subclass of AsyncTask and implement the appropriate callback method from below list.

  • onPreExecute() - This method runs on the UI thread before beginning of background process.
  • doInBackground() - This method runs where real task is taken place. For example if you want to perform complex task, you can do inside this method.
  • publishProgress() - This method called from the doInBackground() method. This will inform UI thread about the background process progress. This method sends information to the UI process.
  • onProgressUpdate() - This method runs on the UI thread whenever the doInBackground() method calls publishProgress(). Use this method to update the progressBar.
  • onPostExecute() - Runs on the UI thread after doInBackground() method completes its operation.
Sample class,

public class SimpleAsyncActivity extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
            CountingTask tsk = new CountingTask();
            tsk.execute();
       }

       private class CountingTask extends AsyncTask<Void, Integer, Integer> {
             CountingTask() {}
            @Override
            protected Integer doInBackground(Void... unused) {
                    int i = 0;                    while (i < 100) {
                            SystemClock.sleep(250);
                            i++;
                            if (i % 5 == 0) {
                                   // update UI with progress every 5%
                                   publishProgress(i);
                            }
                   }
                   return i;
          }

          protected void onProgressUpdate(Integer... progress) {
                   TextView tv = (TextView) findViewById(R.id.counter);
                    tv.setText(progress[0] + "% Complete!");
          }

          protected void onPostExecute(Integer result) {
                   TextView tv = (TextView) findViewById(R.id.counter);
                    tv.setText("Count Complete! Counted to " + result.toString());
           }
     }
}

Comments

Popular posts from this blog

Offers on Friday, April 24, 2020

Fatal: LoadModule: error loading module 'mod_sql_mysql.c'