Updated 11 September 2019
The AsyncTask the class allows to run instructions in the background and to synchronize again with the main thread. It also reports the progress of the running tasks.
You must subclass it so The parameters are the following AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>
and AsyncTask
is started via the execute()
method so this execute()
method calls the doInBackground()
and the onPostExecute()
method.
TypeOfVarArgParams is passed into the doInBackground()
method as input.
The doInBackground()
the method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread
.
The onPostExecute()
method synchronizes itself again with the user interface thread and allows it to be updated.
The following code demonstrates how to use to download something from the Internet. The code requires the android.permission.INTERNET
permission in your Android manifest.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package de.vogella.android.asynctask; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } private class MyAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected String doInBackground(Void void) { // This method is using a worker thread. // We can perform the network calls in this method. } @Override protected void onPostExecute(Void void) { //Get the data from doInBackground method } } // Triggered via a button in your layout public void onClick(View view) { MyAsyncTask task = new MyAsyncTask(); task.execute(); } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.