AsyncTask and AsyncTaskLoader

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Android Developer Fundamentals V2

Background
Tasks

Lesson 7

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
AsyncTaskLoader
License.
7.1 AsyncTask
and
AsyncTaskLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
AsyncTaskLoader
License.
Contents

● Threads
● AsyncTask
● Loaders
● AsyncTaskLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
AsyncTaskLoader
License.
Threads

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
AsyncTaskLoader
License.
The main thread

● Independent path of execution in a running program


● Code is executed line by line
● App runs on Java thread called "main" or "UI thread"
● Draws UI on the screen
● Responds to user actions by handling UI events

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
AsyncTaskLoader
License.
The Main thread must be fast
● Hardware updates screen every 16 milliseconds
● UI thread has 16 ms to do all its work
● If it takes too long, app stutters or hangs
WAI
T

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
AsyncTaskLoader
License.
Users uninstall unresponsive apps
● If the UI waits too long for an
operation to finish, it becomes
unresponsive
● The framework shows an
Application Not Responding
(ANR) dialog

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
AsyncTaskLoader
License.
What is a long running task?
● Network operations
● Long calculations
● Downloading/uploading files
● Processing images
● Loading data

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
AsyncTaskLoader
License.
Background threads
Execute long running tasks on a background thread
Main Thread (UI Thread)
Update UI

● AsyncTask
● The Loader Framework
● Services
Worker Thread Do some work

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
AsyncTaskLoader
License.
Two rules for Android threads

● Do not block the UI thread


○ Complete all work in less than 16 ms for each screen
○ Run slow non-UI work on a non-UI thread

● Do not access the Android UI toolkit from outside


the UI thread
○ Do UI work only on the UI thread

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
AsyncTaskLoader
License.
AsyncTask

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
AsyncTaskLoader
License.
What is AsyncTask?
Use AsyncTask to implement basic background tasks

Main Thread (UI Thread)


onPostExecute()

Worker Thread
doInBackground()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
AsyncTaskLoader
License.
Override two methods

● doInBackground()—runs on a background thread


○ All the work to happen in the background

● onPostExecute()—runs on main thread when work done


○ Process results
○ Publish results to the UI

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
AsyncTaskLoader
License.
AsyncTask helper methods
● onPreExecute()
○ Runs on the main thread
○ Sets up the task

● onProgressUpdate()
○ Runs on the main thread
○ receives calls from publishProgress() from background thread

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
AsyncTaskLoader
License.
AsyncTask helper methods

Main Thread (UI Thread)


onPreExecute() onProgressUpdate() onPostExecute()

Worker Thread publishProgress()

doInBackground()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
AsyncTaskLoader
License.
Creating an AsyncTask
1. Subclass AsyncTask
2. Provide data type sent to doInBackground()
3. Provide data type of progress units for
onProgressUpdate()
4. Provide data type of result for onPostExecute()

private class MyAsyncTask


extends AsyncTask<URL,AsyncTask
Integer,
and
Bitmap> {...} This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
AsyncTaskLoader
License.
MyAsyncTask class definition
private class MyAsyncTask
extends AsyncTask<String, Integer, Bitmap> {...}

doInBackground()
doInBackground()
onProgressUpdate()
doInBackground(
onPostExecute()
● String—could be query, URI for filename
● Integer—percentage completed, steps done
● Bitmap—an image to be displayed
● Use Void if no data passed
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
AsyncTaskLoader
License.
onPreExecute()

protected void onPreExecute() {


// display a progress bar
// show a toast
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
AsyncTaskLoader
License.
doInBackground()

protected Bitmap doInBackground(String... query) {


// Get the bitmap
return bitmap;
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
AsyncTaskLoader
License.
onProgressUpdate()

protected void onProgressUpdate(Integer... progress) {


setProgressPercent(progress[0]);
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
AsyncTaskLoader
License.
onPostExecute()

protected void onPostExecute(Bitmap result) {


// Do something with the bitmap
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
AsyncTaskLoader
License.
Start background work

public void loadImage (View view) {


String query = mEditText.getText().toString();
new MyAsyncTask(query).execute();
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
AsyncTaskLoader
License.
Limitations of AsyncTask
● When device configuration changes, Activity is destroyed
● AsyncTask cannot connect to Activity anymore
● New AsyncTask created for every config change
● Old AsyncTasks stay around
● App may run out of memory or crash

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
AsyncTaskLoader
License.
When to use AsyncTask
● Short or interruptible tasks
● Tasks that do not need to report back to UI or user
● Lower priority tasks that can be left unfinished
● Use AsyncTaskLoader otherwise

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
AsyncTaskLoader
License.
Loaders

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
AsyncTaskLoader
License.
What is a Loader?
● Provides asynchronous loading of data
● Reconnects to Activity after configuration change
● Can monitor changes in data source and deliver new data
● Callbacks implemented in Activity
● Many types of loaders available
○ AsyncTaskLoader, CursorLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
AsyncTaskLoader
License.
Why use loaders?

● Execute tasks OFF the UI thread


● LoaderManager handles configuration changes for you
● Efficiently implemented by the framework
● Users don't have to wait for data to load

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
AsyncTaskLoader
License.
Anatomy
What is a of
LoaderManager?
a Loader

● Manages loader functions via callbacks

● Can manage multiple loaders


○ loader for database data, for AsyncTask data, for internet data…

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
AsyncTaskLoader
License.
Get a loader with initLoader()
● Creates and starts a loader, or reuses an existing one,
including its data
● Use restartLoader() to clear data in existing loader

getLoaderManager().initLoader(Id, args, callback);


getLoaderManager().initLoader(0, null, this);

getSupportLoaderManager().initLoader(0, null, this);

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
AsyncTaskLoader
License.
Implementing
AsyncTaskLoade
r

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
AsyncTaskLoader
License.
AsyncTaskLoader Overview
AsyncTaskLoader AsyncTask WorkToDo

LoaderManager

Request Receive
Work Result

Activity
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
AsyncTaskLoader
License.
AsyncTask AsyncTaskLoader

doInBackground() loadInBackground()
onPostExecute() onLoadFinished()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
AsyncTaskLoader
License.
Steps for AsyncTaskLoader subclass

1. Subclass AsyncTaskLoader
2. Implement constructor
3. loadInBackground()
4. onStartLoading()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
AsyncTaskLoader
License.
Subclass AsyncTaskLoader

public static class StringListLoader


extends AsyncTaskLoader<List<String>> {

public StringListLoader(Context context, String queryString) {


super(context);
mQueryString = queryString;
}
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
AsyncTaskLoader
License.
loadInBackground()

public List<String> loadInBackground() {


List<String> data = new ArrayList<String>;
//TODO: Load the data from the network or from a database
return data;
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 35
AsyncTaskLoader
License.
onStartLoading()
When restartLoader() or initLoader() is called, the
LoaderManager invokes the onStartLoading() callback
● Check for cached data
● Start observing the data source (if needed)
● Call forceLoad() to load the data if there are changes or
no cached data
protected void onStartLoading() { forceLoad(); }
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 36
AsyncTaskLoader
License.
Implement loader callbacks in Activity
● onCreateLoader() — Create and return a new Loader for
the given ID
● onLoadFinished() — Called when a previously created
loader has finished its load
● onLoaderReset() — Called when a previously created
loader is being reset making its data unavailable

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 37
AsyncTaskLoader
License.
onCreateLoader()

@Override
public Loader<List<String>> onCreateLoader(int id, Bundle args) {
return new StringListLoader(this,args.getString("queryString"));
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 38
AsyncTaskLoader
License.
onLoadFinished()

Results of loadInBackground() are passed to


onLoadFinished() where you can display them

public void onLoadFinished(Loader<List<String>> loader,


List<String> data) {
mAdapter.setData(data);
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 39
AsyncTaskLoader
License.
onLoaderReset()
● Only called when loader is destroyed
● Leave blank most of the time

@Override
public void onLoaderReset(final LoaderList<String>> loader) { }

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 40
AsyncTaskLoader
License.
Get a loader with initLoader()
● In Activity
● Use support library to be compatible with more devices

getSupportLoaderManager().initLoader(0, null, this);

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 41
AsyncTaskLoader
License.
Learn more
● AsyncTask Reference
● AsyncTaskLoader Reference
● LoaderManager Reference
● Processes and Threads Guide
● Loaders Guide
● UI Thread Performance: Exceed the Android Speed Limit
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 42
AsyncTaskLoader
License.
What's Next?

● Concept Chapter: 7.1 AsyncTask and AsyncTaskLoader


● Practical: 7.1 AsyncTask

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 43
AsyncTaskLoader
License.
END

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 44
AsyncTaskLoader
License.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy