Intro To Android (Workbook 2)

AsyncTask

Resources

Threading & Lifecycle

You create and run async tasks on the main UI thread. You can only run the task once, if you want to run a similar task,you'll need to create a new one.

Note: AsyncTask's are tied to the Activity lifecycle and will be destroyed on configuration changes, etc. This example shows how to store and restore an AsyncTask: Shelves

Code

public class DownloadFileTask extends AsyncTask<String, Void, String>
{
    @Override
    protected void onPreExecute()
    {
        // What to do before starting
        // Example: Start a loading indicator
    }

    @Override
    protected String doInBackground( String... urls )
    {
        // The background work to be completed
        // Example: Fetch data from the web and process
    }

    @Override
    protected void onProgressUpdate( Void... values )
    {
        // What to show the user during processing
        // Example: Update percentage of download complete
    }

    @Override
    protected void onPostExecute( String result )
    {
        // What to do when done
        // Example: Post notification to Otto bus
    }
}

Running

new DownloadFileTask().execute(url);

Testing

public class DownloadFileTaskTest
{
    private BusHelper  helper;

    @Before
    public void setUp() throws Exception
    {
        DownloadFileTask task = getDownloadFileTask();

        Robolectric.getBackgroundScheduler().runOneTask();
        Robolectric.getUiThreadScheduler().runOneTask();

        helper = new BusHelper();
        LocalFoodApplication.getInstance().getBus().register( helper );

        task.execute();
    }

    @Test
    public void shouldPostLocationListAvailableWhenDone()
    {
        assertTrue( helper.getLastEvent() instanceof LocationListAvailable );
    }

    private DownloadFileTask getDownloadFileTask()
    {
        return new DownloadFileTask()
        {
            @Override
            protected String doInBackground( String... urls )
            {
                return null;
            }
        };
    }
}