AsyncTask (Associate Android Developer Certification)

Source: http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

AsyncTask should be used for short time operations. It can update UI. When you call method execute – AsyncTask starts. It runs on different thread.

AsyncTask has 3 parameters:

AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue>

TypeOfVarArgParams – input for method doInBackground
ProgressValue – for progress information
ResultValue – result of doInBackground method

Parallel execution:

// ImageLoader extends AsyncTask
ImageLoader imageLoader = new ImageLoader( imageView );

// Execute in parallel
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );

Problem with AsyncTask is it cannot handle application configuration changes(orientation change for example).

AsyncTask example:

public class MainActivity extends Activity {
    private TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.TextView01);
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            // we use the OkHttp library from https://github.com/square/okhttp
            try {
                OkHttpClient client = new OkHttpClient();
                Request request =
                        new Request.Builder()
                                .url(urls[0])
                                .build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    return response.body().string();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "Download failed";
        }


        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
        }
    }




    public void onClick(View view) {
        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.vogella.com/index.html" });

    }
}