2. Today’s agenda
Why it is important to run network operations on separate thread?
Network operations in background.
AsyncTask.
Parsing different data formats: Json.
--
3. Threads
“A sequence of execution.”
There can be more than one thread of execution to achieve multiple tasks
simultaneously.
This is called “multi-threading”.
Multithreading helps in optimal usage of resources and time.
Java has inherent support for multithreading.
4. Android - The UI Thread
There is 1 main thread in Android application.
This main thread is also called “The UI Thread”.
The UI thread is responsible for the user’s interaction with UI.
It handles all the button clicks, animations, displaying data and images on UI etc.
The UI thread should not be kept busy for other long running operations.
5. UI thread is only for UI operations
Should not do any long running operation on
UI thread.
Avoid these operations on UI thread:
● Get data from internet.
● Read file from permanent storage.
● Do heavy calculations.
● Parse large data.
6. Responsiveness
You want to make your app responsive.
Responsiveness = smooth user experience.
Delay in response to user action = bad user experience.
Delay can lead to ANR (Application Not Responding) or even crash.
7. Network operations
Do not ever do Internet operation on main thread.
It will also lead to “NetworkOnMainThread” exception.
Use a worker thread for all network operations.
But, update to UI can only happen on UI thread.
When operation is complete. Give the result back to UI thread.
● Handlers
● AsyncTasks
8. AsyncTask
private class MyLongRunningTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
// Do network operation
}
protected void onProgressUpdate(Integer... progress) {
// update progress on UI
}
protected void onPostExecute(Long result) {
// Finally display the end result on UI
}
}
9. AsyncTask
doInBackground(): For doing long running background task.
onProgressUpdate(): For showing the progress of the background task on UI. E.g.
percentage of downloaded file.
onPostExecute(): Finally showing the result of the task completed.
11. Json
Lightweight data format.
Easy to read and edit for humans.
Either a collection of key-value pairs or a list of values.
Used to transfer data from server to client in
Web-services.
14. About Me
Paramvir Singh, Android Developer and Trainer
paramvir.singh88@gmail.com
https://in.linkedin.com/in/paramvir-singh-android-developer-b45b5321