Network calls and heavy operations cannot be performed in the main UI thread, as they will make the application unresponsive. These have to be executed in a background thread, and one of the mechanisms to achieve this is called AsyncTask. AsyncTask is an Android component for handling thread creation and execution and is well suitable for tasks such as communication with REST APIs. Alternatives to AsyncTask can be to use Threads, Runnables or third-party frameworks such as Retrofit (Consume REST APIs with Retrofit).
The code snippet below shows how to create an AsyncTask for searching for a Spotify track. The TrackSearchAsyncTask is created by extending AsyncTask and using three parameters:
AsyncTask
Params - the input value to the execute() method, in this case a String value for song name.
Progress - a value that can be used to update progress. In this case a Void value.
Result - The result returned to the main UI thread, in this case a TrackSearchResult with the found songs.
TrackSearchAsyncTask overrides three methods:
onPreExecute - runs in the main UI thread. Used for setup of the SearchService.
doInBackground - runs in a background thread, and performs the search for tracks.
onPostExecute - runs in the main UI thread. Gets the result from doInBackground and sends these to a new activity
privateclassTrackSearchAsyncTaskextendsAsyncTask<String,Void,TrackSearchResult>{privateSearchServicesearchService;@OverrideprotectedvoidonPreExecute(){super.onPreExecute();searchService=newSearchService();}@OverrideprotectedTrackSearchResultdoInBackground(String...params){// Perform search for tracks in SpotifyreturnsearchService.searchForTrack(params[0]);}@OverrideprotectedvoidonPostExecute(TrackSearchResultresult){ArrayList<Track>tracks=newArrayList<Track>();tracks.addAll(result.getTracks());// Start result activity which displays the result.IntentresultActivity=newIntent(getApplicationContext(),ResultActivity.class);// Add the search result as a parcelable extraresultActivity.putParcelableArrayListExtra("tracks",tracks);startActivity(resultActivity);}}