Android Developer Fundamentals V 2 Background Tasks Android
Android Developer Fundamentals V 2 Background Tasks Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 1
Threads Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 2
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 Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 3
The Main thread must be fast ● Hardware updates screen every 16 ms ● UI thread has 16 ms to do all its work ● If it takes too long, app stutters or hangs ● If the UI waits too long for an operation to finish, it becomes unresponsive ● The framework shows an Application Not Responding (ANR) dialog Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 4
What is a long running task? ● Network operations ● Long calculations ● Downloading/uploading files ● Processing images ● Loading data Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 5
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 Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 6
Background threads • Execute long running tasks on a background (worker) thread • A worker thread is any thread which is not the main or UI thread. Main Thread (UI Thread) Update UI ● Async. Task ● The Loader Framework ● Services Worker Thread Android Developer Fundamentals V 2 Do some work Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 7
Async. Task Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 8
What is Async. Task? Use Async. Task to implement basic background tasks Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 9
Override two methods ● do. In. Background()—runs on a background thread ○ All the work to happen in the background ● on. Post. Execute()—runs on main thread when work done ○ Process results ○ Publish results to the UI Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 10
Async. Task helper methods ● on. Pre. Execute() ○ Runs on the main thread ○ Sets up the task ● on. Progress. Update() ○ Runs on the main thread ○ receives calls from publish. Progress() from background thread Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 11
Creating an Async. Task 1. Subclass Async. Task 2. Provide data type sent to do. In. Background() 3. Provide data type of progress units for on. Progress. Update() 4. Provide data type of result for on. Post. Execute() Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 12
My. Async. Task class definition private class My. Async. Task extends Async. Task<String, Integer, Bitmap> {. . . } do. In. Background() on. Progress. Update() do. In. Background( ● String—could be query, URI for filename ● Integer—percentage completed, steps done ● Bitmap—an image to be displayed ● Use Void if no data passed Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader on. Post. Execute() This work is licensed under a Creative Commons Attribution 4. 0 International License. 13
do. In. Background() protected void on. Pre. Execute() { // display a progress bar } protected Bitmap do. In. Background(String. . . query ) { // Get the bitmap return bitmap; } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 14
do. In. Background() protected void on. Progress. Update(Integer. . . progress ) { set. Progress. Percent(progress[0]); } protected void on. Post. Execute(Bitmap result ) { // Do something with the bitmap } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 15
Start background work public void load. Image (View view) { String query = m. Edit. Text. get. Text(). to. String(); new My. Async. Task(query). execute(); } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 16
Start background work public class Download. Files. Task extends Async. Task<URL, Integer, Long> { protected Long do. In. Background(URL. . . urls) { int count = urls. length; long total. Size = 0; for (int i = 0; i < count; i++) { total. Size += Downloader. download. File(urls[i]); publish. Progress((int) ((i / (float) count) * 100)); if (is. Cancelled()) break; } return total. Size; } protected void on. Progress. Update(Integer. . . progress) { protected void on. Post. Execute(Long result) { set. Progress. Percent(progress[0]); } show. Dialog("Downloaded " + result + " bytes"); } } new Download. Files. Task(). execute(url 1, url 2, url 3); Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 17
Cancelling an Async. Task • We cancel a task at any time by invoking the cancel() method. • The cancel() method returns false if the task could not be cancelled, typically because it has already completed. • To find out whether a task has been cancelled, check the return value of is. Cancelled() periodically from do. In. Background. • After an Async. Task task is cancelled, on. Post. Execute() will not be invoked after do. In. Background() returns. • Instead, on. Cancelled(Object) is invoked. Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 18
Limitations of Async. Task ● When device configuration changes, Activity is destroyed ● Async. Task cannot connect to Activity anymore ● New Async. Task created for every config change ● Old Async. Tasks stay around ● App may run out of memory or crash Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 19
Loaders Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 20
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 ○ Async. Task. Loader, Cursor. Loader Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 21
Anatomy What is a of Loader. Manager? a Loader ● Manages loader functions via callbacks ● Can manage multiple loaders ○ loader for database data, for Async. Task data, for internet data… Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 22
Get a loader with init. Loader() ● Creates and starts a loader, or reuses an existing one, including its data ● Use restart. Loader() to clear data in existing loader get. Loader. Manager(). init. Loader(Id, args, callback); get. Loader. Manager(). init. Loader(0, null, this); get. Support. Loader. Manager(). init. Loader(0, null, this); Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 23
Implementing Async. Task. Loader Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 24
Async. Task. Loader Overview Async. Task. Loader Async. Task Work. To. Do Loader. Manager Request Work Receive Result Activity Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 25
Async. Task. Loader do. In. Background() load. In. Background() on. Post. Execute() on. Load. Finished() Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 26
Steps for Async. Task. Loader subclass 1. Subclass Async. Task. Loader 2. Implement constructor 3. load. In. Background() 4. on. Start. Loading() Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 27
Subclass Async. Task. Loader public static class String. List. Loader extends Async. Task. Loader <List<String>> { public String. List. Loader (Context context, String query. String) { super(context); m. Query. String = query. String; } } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 28
load. In. Background() public List<String> load. In. Background() { List<String> data = new Array. List<String>(); //TODO: Load the data from the network or from a database return data; } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 29
on. Start. Loading() When restart. Loader() or init. Loader() is called, the Loader. Manager invokes the on. Start. Loading() callback ● Check for cached data ● Start observing the data source (if needed) ● Call force. Load() to load the data if there are changes or no cached data protected void on. Start. Loading() { Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader force. Load(); This work is licensed under a Creative Commons Attribution 4. 0 International License. } 30
Implement loader callbacks in Activity ● on. Create. Loader() — Create and return a new Loader for the given ID ● on. Load. Finished() — Called when a previously created loader has finished its load ● on. Loader. Reset() — Called when a previously created loader is being reset making its data unavailable Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 31
on. Create. Loader() @Override public Loader<List<String>> on. Create. Loader(int id, Bundle args) { return new String. List. Loader(this, args. get. String("query. String")); } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 32
on. Load. Finished() Results of load. In. Background() are passed to on. Load. Finished() where you can display them public void on. Load. Finished(Loader<List<String>> loader, List<String> data) { m. Adapter. set. Data(data); } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 33
on. Loader. Reset() ● Only called when loader is destroyed ● Leave blank most of the time @Override public void on. Loader. Reset(final Loader<List<String>> loader) { } Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 34
Get a loader with init. Loader() ● In Activity ● Use support library to be compatible with more devices get. Support. Loader. Manager(). init. Loader(0, null, this); Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 35
END Android Developer Fundamentals V 2 Async. Task and Async. Task. Loader This work is licensed under a Creative Commons Attribution 4. 0 International License. 36
- Slides: 36