0% found this document useful (0 votes)
19 views44 pages

07.1 AsyncTask and AsyncTaskLoader

Uploaded by

bmwli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views44 pages

07.1 AsyncTask and AsyncTaskLoader

Uploaded by

bmwli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Android Developer Fundamentals V2

Background
Tasks

Lesson 7

AsyncTask and This work is licensed under a


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

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 2
Fundamentals V2 International License
Contents

● Threads
● AsyncTask
● Loaders
● AsyncTaskLoader

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 3
Fundamentals V2 International License
Threads

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 4
Fundamentals V2 International 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
Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 5
Fundamentals V2 International 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

WAIT

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 6
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 7
Fundamentals V2 International 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


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

● AsyncTask
● The Loader Framework
Do some
● Services Worker Thread work
AsyncTask and This work is licensed under a
Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 9
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 10
Fundamentals V2 International License
AsyncTask

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 11
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 12
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 13
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 14
Fundamentals V2 International License
AsyncTask helper methods

Main Thread (UI Thread)


onPreExecute() onProgressUpdate onPostExecute()
()

Worker Thread publishProgress(


)
doInBackground()

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 15
Fundamentals V2 International 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, Integer, Bitmap>
This work is licensed under a
AsyncTask and
{...} Android Developer
Fundamentals V2
Creative Commons Attribution 4.0
AsyncTaskLoad
International License
16
MyAsyncTask class definition
private class MyAsyncTask
extends AsyncTask<String, Integer, Bitmap>
{...}
doInBackground()
onProgressUpdate
doInBackground()
() onPostExecute()
doInBackground(

● String—could be query, URI for filename


● Integer—percentage completed, steps done
● Bitmap—an image to be displayed This work is licensed under a
AsyncTask and
● Use Void if no data
Android passed
Developer AsyncTaskLoad
Creative Commons Attribution 4.0
International License
17
Fundamentals V2
onPreExecute()

protected void onPreExecute() {


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

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 18
Fundamentals V2 International License
doInBackground()

protected Bitmap doInBackground(String... query) {


// Get the bitmap
return bitmap;
}

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 19
Fundamentals V2 International License
onProgressUpdate()

protected void onProgressUpdate(Integer... progress) {


setProgressPercent(progress[0]);
}

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 20
Fundamentals V2 International License
onPostExecute()

protected void onPostExecute(Bitmap result) {


// Do something with the bitmap
}

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 21
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 22
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 23
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 24
Fundamentals V2 International License
Loaders

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 25
Fundamentals V2 International 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
AsyncTask and This work is licensed under a
○ AsyncTaskLoader, CursorLoader
Android Developer
Fundamentals V2
AsyncTaskLoad
Creative Commons Attribution 4.0
International License
26
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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 27
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 28
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 29
Fundamentals V2 International License
Implementing
AsyncTaskLoa
der

AsyncTask and This work is licensed under a


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

LoaderManager

Request Receive
Work Result

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

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

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 32
Fundamentals V2 International License
Steps for AsyncTaskLoader
subclass
1. Subclass AsyncTaskLoader
2. Implement constructor
3.loadInBackground()
4.onStartLoading()

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 33
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 34
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 35
Fundamentals V2 International 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() This work is licensed under a
AsyncTask and
Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 36
Fundamentals V2 International 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
Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 37
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 38
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 39
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 40
Fundamentals V2 International 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


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 41
Fundamentals V2 International 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
Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 42
Fundamentals V2 International License
What's Next?

● Concept Chapter:
7.1 AsyncTask and AsyncTaskLoader
● Practical: 7.1 AsyncTask

AsyncTask and This work is licensed under a


Android Developer AsyncTaskLoad
Creative Commons Attribution 4.0 43
Fundamentals V2 International License
END

AsyncTask and This work is licensed under a


Android Developer Creative Commons Attribution 4.0
AsyncTaskLoad International License 44
Fundamentals V2

You might also like