Lesson 86. AsyncTask. Dating, a simple example

Lesson 86. AsyncTask. Dating, a simple example


In this lesson:

– create a simple example from AsyncTask

In the past lessons, we have looked at how the application can accomplish difficult tasks. We introduced them into a separate one flow and used Handler for feedback and screen updates. Android creators have decided that these mechanisms should be separated into a separate class – AsyncTask. That is, its purpose is to accomplish difficult tasks and transfer the results of work to the UI-stream. But we don’t have to think about creating a Handler and a new thread.

In order to work with AsyncTask, you need to create a successor class and write in it the implementation of the methods we need. In this lesson, we look at three methods:

doInBackground – will be executed in a new stream, here we solve all our difficult tasks. Because the stream is not the primary one, it does not have access to the UI.

onPreExecute – Runs before doInBackground, has UI access

onPostExecute – Runs after doInBackground (does not work if AsyncTask was canceled – in the following lessons), has UI access

Let’s make a simple application that uses the above methods. Display the word Begin in the onPreExecute method, emulating heavy code in the doInBackground method, display the word End in the onPostExecute method.

Let’s create a project:

Project name: P0861_AsyncTask
Build Target: Android 2.3.3
Application name: AsyncTask
Package name: en.startandroid.develop.p0861asynctask
Create Activity: MainActivity

strings.xml:



	AsyncTask
	Start

main.xml:



	
	
	
	
	

Pressing the button will start the task in TextView to display information. ProgressBar will show that the program does not “hang” at runtime.

MainActivity.java:

package ru.startandroid.develop.p0861asynctask;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

  MyTask mt;
  TextView tvInfo;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvInfo = (TextView) findViewById(R.id.tvInfo);
  }

  public void onclick(View v) {
    mt = new MyTask();
    mt.execute();
  }

  class MyTask extends AsyncTask {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      tvInfo.setText("Begin");
    }

    @Override
    protected Void doInBackground(Void... params) {
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return null;
    }

    @Override
    protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      tvInfo.setText("End");
    }
  }
}

In the method onclick we create a MyTask object and execute it using the execute method.

MyTask is our class that inherits AsyncTask. We prescribe our code in it.

In the method onPreExecute print Begin text.

In the method doInBackground emulating heavy code – pauses for two seconds.

In the method onPostExecute output the text End.

We will save everything and launch the application. press Start, Begin text appears

ProgressBar runs, so the main stream (responsible for the UI) is free.

After two seconds, the text End appears

We have got a new task flow and access to UI working. However, they did not create threads and Handler, He did everything for us AsyncTask.

Of the methods considered, it is necessary to implement only doInBackground. The other two are optional.

This example shows the simplest possibilities. We’ve used Void everywhere to not mess with parameters. We will look at these and other options in more detail in the following lessons. For now it is necessary to learn in what sequence and in what streams the AsyncTask methods considered by us are executed.

Note that if we click on Start while AsyncTask is running, a new AsyncTask will be created and launched. But the old man will not go anywhere, and will continue to work in his stream. That is, they will both work and update the same screen. Later we will find out how to handle it.

Official help gives 4 rules using AsyncTask, I’ll also list them here:

– The AsyncTask object must be created in the UI thread

– the execute method must be called in the UI thread

– does not directly invoke the methods onPreExecute, doInBackground, onPostExecute and onProgressUpdate (the latter we have not yet passed)

– AsyncTask can be started (execute) only once, otherwise there will be an exception

In the next lesson:

– we use parameters
– output intermediate results




Discuss in the forum [57 replies]

Leave a Comment