Android Connecting To Internet (2)
AndroidConnecting To Internet (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.
--
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.
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.
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.
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.
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
● post() methods
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
}
}
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.
Data Formats
Simple text
Json
XML
Images
Audio/Video file
InputStream
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.
Parsing Json Data{
"firstName":"Paramvir",
"lastName":"Singh",
"address":{"streetAddress":"Street no. 123","city":"Gurgaon","state":"HR","postalCode":"122002"
},"phoneNumbers":[
{"type":"home","number":"123456"
},{
"type":"office","number":"22-333-44"
}],
"children":[],}
Next..
Handlers
Loading images from web
Limitations and common problems in connectivity
Services
***
About Me
Paramvir Singh, Android Developer and Trainer
https://in.linkedin.com/in/paramvir-singh-android-developer-b45b5321