Date Archives July 23, 2016

AsyncTask

Screen Shot 2016-07-22 at 11.57.54 PM

Work flow

  1. Asynctask starts with execute() method.
  2. Before starting Asynctask background, onPreExecuted() executes first.  Usually, people put loading images.
  3. Doing background work in new thread, gets parameter when execute() was executed.
  4. in doInBackground(), process status is updated by using publishProgress() method.
  5. onProgressUpdate() is automatically called whenever publishProgress() is executed.
  6. After doInBackground(), result parameter is returned to onPostExecuted(). With the result value, you make code which is executed after thread process is over.

The main point is onPreExecuted(), doInBackground(), and onPostExecuted().

Asynctask() cannot be used inside another Asynctask(). (Use thread or Runnable for other one)

Asynctask<Params,Progress,Result>

  • Params: doInBackground()’s parameter type, and execute() method’s parameter type.
  • Progress: When doInBackground(), process unit type which is onProgressUpdate()’s parameter type.
  • Result: return type of doInBackground(), and parameter type of onPostExecute().

Example…


public class MainActivity extends Activity{

   @Override
   protected void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   // if button clicked, execute AsyncTask with the address
   public void OnClick(View view){
      switch(view.getId()){
         case R.id.button:
            try{
               new DownloadFilesTask().execute(new URL(" address "));
            } catch (MalformedURLException e){
               e.printStackTrace();
            }
            break;
      }
   }

   private class DownloadFilesTask extends AsyncTask<url, integer,long>{

      @Override
      protected void onPreExecute(){
         super.onPreExcute();
      }

      @Override
      protected Long doInBackground(URL... urls){
         // use transferred url
         return total;
      }

      @Override
      protected void onProgressUpdate(Integer... progress){
         // file download percentage
      }

      @Override
      protected void onPostExecute(Long result){
         // use total value from doInBackground
      }

   }

}