AsyncTask

Only the original thread that created a view hierarchy can touch its views.
There are other ways to access to the UI from separate threads
fabiodelorenzo
Posts: 65
Joined: Thu Oct 03, 2013 5:54 pm

AsyncTask

Postby fabiodelorenzo » Thu Oct 03, 2013 6:17 pm

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
An asynchronous task is defined by 3 generic types, called Params, Progress and Result,
Keep in mind they are passed as array (...) so params is params[]
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.


and 4 steps, called : onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Code: Select all

protected class MyAsyncTask extends AsyncTask<Integer, String, Long> {

   @Override
       protected Long doInBackground(Integer... params) {
         int count = 0
         while(taskRunning)
         {
              publishProgress("my progress, count="+Integer.ToString(count) );
              try {
           Thread.sleep(1000);
         } catch (InterruptedException e) {
           Log.d(TAG, "doInBackground exception");
         }
         }
         return count;
       }

   @Override
   protected void onProgressUpdate(String... progress) {
   }

   @Override
   protected void onPostExecute(Long result) {
   }
}


to instantiate the AsyncTask:
taskRunning = true;
new DownloadFilesTask().execute(Integer1, Integer2, Integer3, Integer4);

to stop the AsyncTask:
taskRunning = false;

Return to “access to the UI from a thread”

Who is online

Users browsing this forum: No registered users and 0 guests