SlideShare a Scribd company logo
Networking
How to manage data from WEB
+RobertoOrgiu
@_tiwiz
+MatteoBonifazi
@mbonifazi
Building for Billions
To succeed in the current market, app must provide a
better experience for users who may be connecting to
slower networks
For media rich applications, BITMAPS are
everywhere.
Check a Device's Network Connection
Network connections
Device has various types of network connections
Before performing network operations, it's good practice to
check the state of network connectivity:
● ConnectivityManager: Answers queries about the state of
network connectivity. It also notifies applications when
network connectivity changes.
● NetworkInfo: Describes the status of a network interface
of a given type (currently either Mobile or Wi-Fi).
Check network connections
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);
To perform network operations your app must
declare the following permission in the
AndroidManifest.xml
Connecting to the Network
Secure Network Communication
Ensure data and information stays safe in the app
● Minimize the amount of sensitive or personal user data that you
transmit over the network.
● Send all network traffic from your app over SSL.
● Consider creating a network security configuration, which allows
your app to trust custom CAs or restrict the set of system CAs
that it trusts for secure communication.
Choose an HTTP Client
● HttpsURLConnection client, which supports TLS, streaming
uploads and downloads, configurable timeouts, IPv6, and
connection pooling.
● Apache client is not supported anymore.Avoid it!
Network Operations on a Separate Thread
Network operations can involve unpredictable delay.To avoid
creating an unresponsive UI, don't perform network operations
on the UI thread.
HttpUrlConnection example (1 / 2)
private String downloadUrl(URL url) throws IOException {
try {
connection = (HttpsURLConnection) url.openConnection();
connection.setReadTimeout(3000);
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");
// Open communications link (network traffic occurs here).
connection.connect();
….
HttpUrlConnection example (2 / 2)
….
int responseCode = connection.getResponseCode();
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw new IOException("HTTP error code: " + responseCode);
}
InputStream stream = connection.getInputStream();
if (stream != null) {
String result = readStream(stream, ...);
}
} finally { // Close Stream and disconnect HTTPS connection.
if (stream != null) { stream.close(); }
if (connection != null) { connection.disconnect(); }
}
return result;
}
Data exchange
Network Architecture and Data exchange
Read Json answer
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
…..
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");}
} catch (final JSONException e) {...}
Going forward
Youtube Video
https://www.youtube.com/watch?v=l5mE3Tpjejs
https://www.youtube.com/watch?v=Ecz5WDZoJok
Reference Link
https://developer.android.com/training/basics/network-ops/managing.html
https://developer.android.com/training/basics/network-ops/connecting.html
http://www.slideshare.net/anoochit/slide06-18151934
Is there something easier?
Help from the outside
Retrofit
https://square.github.io/retrofit/
Gson
https://github.com/google/gson
Retrofit (1/3)
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
Retrofit (2/3)
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
Retrofit (3/3)
Call<List<Repo>> repos = service.listRepos("octocat");
Gson
Gson gson = new Gson();
String json = gson.toJson(myRepo);
Repo myRepo = gson.fromJson(jsonString, Repo.class);
Retrofit + Gson
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
Retrofit + Converters
● Gson
● Jackson
● Moshi
● Protobuf
● Wire
● Simple XML
● Scalars
Retrofit + Gson + Gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
+MatteoBonifazi
@mbonifazi
Thank You!
+RobertoOrgiu
@_tiwiz

More Related Content

What's hot

Android application structure
Android application structureAndroid application structure
Android application structure
Alexey Ustenko
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle
瑋琮 林
 

What's hot (20)

Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestate
 
Android application structure
Android application structureAndroid application structure
Android application structure
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
 
Android Services
Android ServicesAndroid Services
Android Services
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Fragment
Fragment Fragment
Fragment
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Android intents
Android intentsAndroid intents
Android intents
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 

Similar to Android Networking

Communication in android
Communication in androidCommunication in android
Communication in android
eleksdev
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
Mu Chun Wang
 
Assistive Technology_Research
Assistive Technology_ResearchAssistive Technology_Research
Assistive Technology_Research
Meng Kry
 

Similar to Android Networking (20)

Communication in android
Communication in androidCommunication in android
Communication in android
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile Devices
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
Statying Alive - Online and OFfline
Statying Alive - Online and OFflineStatying Alive - Online and OFfline
Statying Alive - Online and OFfline
 
Assistive Technology_Research
Assistive Technology_ResearchAssistive Technology_Research
Assistive Technology_Research
 
Application Continuity with Oracle DB 12c
Application Continuity with Oracle DB 12c Application Continuity with Oracle DB 12c
Application Continuity with Oracle DB 12c
 
Android chapter18 c-internet-web-services
Android chapter18 c-internet-web-servicesAndroid chapter18 c-internet-web-services
Android chapter18 c-internet-web-services
 
Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)
 
Ki3517881791
Ki3517881791Ki3517881791
Ki3517881791
 
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATAANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA
 
Sockets
SocketsSockets
Sockets
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_application
 
Lecture 3_IoT.pptx
Lecture 3_IoT.pptxLecture 3_IoT.pptx
Lecture 3_IoT.pptx
 
Android networking in Hindi
Android networking in Hindi Android networking in Hindi
Android networking in Hindi
 
Performance #4 network
Performance #4  networkPerformance #4  network
Performance #4 network
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Configuring LIFA for remote communication using web architecture
Configuring LIFA for remote communication using web architecture Configuring LIFA for remote communication using web architecture
Configuring LIFA for remote communication using web architecture
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers
 
Development of A web and GSM Based Monitoring and Controlling System for PLC ...
Development of A web and GSM Based Monitoring and Controlling System for PLC ...Development of A web and GSM Based Monitoring and Controlling System for PLC ...
Development of A web and GSM Based Monitoring and Controlling System for PLC ...
 

More from Matteo Bonifazi

More from Matteo Bonifazi (17)

Invading the home screen
Invading the home screenInvading the home screen
Invading the home screen
 
Engage user with actions
Engage user with actionsEngage user with actions
Engage user with actions
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java stars
 
Android JET Navigation
Android JET NavigationAndroid JET Navigation
Android JET Navigation
 
Firebase-ized your mobile app
Firebase-ized  your mobile appFirebase-ized  your mobile app
Firebase-ized your mobile app
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying images
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
Android things intro
Android things introAndroid things intro
Android things intro
 
The Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHThe Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CH
 
Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016
 
UaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIUaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing API
 
The unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingThe unconventional devices for the Android video streaming
The unconventional devices for the Android video streaming
 
Google IO - Five months later
Google IO - Five months laterGoogle IO - Five months later
Google IO - Five months later
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devices
 
Enlarge your screen
Enlarge your screenEnlarge your screen
Enlarge your screen
 

Recently uploaded

一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
aagad
 
Article writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxArticle writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptx
abhinandnam9997
 

Recently uploaded (12)

How Do I Begin the Linksys Velop Setup Process?
How Do I Begin the Linksys Velop Setup Process?How Do I Begin the Linksys Velop Setup Process?
How Do I Begin the Linksys Velop Setup Process?
 
The Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyThe Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case Study
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
 
Pvtaan Social media marketing proposal.pdf
Pvtaan Social media marketing proposal.pdfPvtaan Social media marketing proposal.pdf
Pvtaan Social media marketing proposal.pdf
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
The AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfThe AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdf
 
The Best AI Powered Software - Intellivid AI Studio
The Best AI Powered Software - Intellivid AI StudioThe Best AI Powered Software - Intellivid AI Studio
The Best AI Powered Software - Intellivid AI Studio
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
Article writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxArticle writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 

Android Networking

  • 1. Networking How to manage data from WEB +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi
  • 2. Building for Billions To succeed in the current market, app must provide a better experience for users who may be connecting to slower networks
  • 3. For media rich applications, BITMAPS are everywhere.
  • 4. Check a Device's Network Connection
  • 5. Network connections Device has various types of network connections Before performing network operations, it's good practice to check the state of network connectivity: ● ConnectivityManager: Answers queries about the state of network connectivity. It also notifies applications when network connectivity changes. ● NetworkInfo: Describes the status of a network interface of a given type (currently either Mobile or Wi-Fi).
  • 6. Check network connections <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isWifiConn = networkInfo.isConnected(); networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isMobileConn = networkInfo.isConnected(); Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn); Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn); To perform network operations your app must declare the following permission in the AndroidManifest.xml
  • 8. Secure Network Communication Ensure data and information stays safe in the app ● Minimize the amount of sensitive or personal user data that you transmit over the network. ● Send all network traffic from your app over SSL. ● Consider creating a network security configuration, which allows your app to trust custom CAs or restrict the set of system CAs that it trusts for secure communication.
  • 9. Choose an HTTP Client ● HttpsURLConnection client, which supports TLS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. ● Apache client is not supported anymore.Avoid it! Network Operations on a Separate Thread Network operations can involve unpredictable delay.To avoid creating an unresponsive UI, don't perform network operations on the UI thread.
  • 10. HttpUrlConnection example (1 / 2) private String downloadUrl(URL url) throws IOException { try { connection = (HttpsURLConnection) url.openConnection(); connection.setReadTimeout(3000); connection.setConnectTimeout(3000); connection.setRequestMethod("GET"); // Open communications link (network traffic occurs here). connection.connect(); ….
  • 11. HttpUrlConnection example (2 / 2) …. int responseCode = connection.getResponseCode(); if (responseCode != HttpsURLConnection.HTTP_OK) { throw new IOException("HTTP error code: " + responseCode); } InputStream stream = connection.getInputStream(); if (stream != null) { String result = readStream(stream, ...); } } finally { // Close Stream and disconnect HTTPS connection. if (stream != null) { stream.close(); } if (connection != null) { connection.disconnect(); } } return result; }
  • 13. Network Architecture and Data exchange
  • 14. Read Json answer String jsonStr = result; try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); ….. // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile");} } catch (final JSONException e) {...}
  • 15. Going forward Youtube Video https://www.youtube.com/watch?v=l5mE3Tpjejs https://www.youtube.com/watch?v=Ecz5WDZoJok Reference Link https://developer.android.com/training/basics/network-ops/managing.html https://developer.android.com/training/basics/network-ops/connecting.html http://www.slideshare.net/anoochit/slide06-18151934
  • 17. Help from the outside Retrofit https://square.github.io/retrofit/ Gson https://github.com/google/gson
  • 18. Retrofit (1/3) public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }
  • 19. Retrofit (2/3) Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); GitHubService service = retrofit.create(GitHubService.class);
  • 20. Retrofit (3/3) Call<List<Repo>> repos = service.listRepos("octocat");
  • 21. Gson Gson gson = new Gson(); String json = gson.toJson(myRepo); Repo myRepo = gson.fromJson(jsonString, Repo.class);
  • 22. Retrofit + Gson Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); GitHubService service = retrofit.create(GitHubService.class);
  • 23. Retrofit + Converters ● Gson ● Jackson ● Moshi ● Protobuf ● Wire ● Simple XML ● Scalars
  • 24. Retrofit + Gson + Gradle compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.google.code.gson:gson:2.8.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0'