Upload
matteo-bonifazi
View
77
Download
0
Embed Size (px)
Citation preview
NetworkingHow to manage data from WEB
+RobertoOrgiu@_tiwiz
+MatteoBonifazi@mbonifazi
Building for BillionsTo 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 connectionsDevice 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 CommunicationEnsure 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 Videohttps://www.youtube.com/watch?v=l5mE3Tpjejshttps://www.youtube.com/watch?v=Ecz5WDZoJok
Reference Linkhttps://developer.android.com/training/basics/network-ops/managing.htmlhttps://developer.android.com/training/basics/network-ops/connecting.htmlhttp://www.slideshare.net/anoochit/slide06-18151934
Is there something easier?
Help from the outside
Retrofithttps://square.github.io/retrofit/
Gsonhttps://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