25
Networking How to manage data from WEB +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi

Android Networking

Embed Size (px)

Citation preview

Page 1: Android Networking

NetworkingHow to manage data from WEB

+RobertoOrgiu@_tiwiz

+MatteoBonifazi@mbonifazi

Page 2: Android Networking

Building for BillionsTo succeed in the current market, app must provide a better experience for users who may be connecting to

slower networks

Page 3: Android Networking

For media rich applications, BITMAPS are everywhere.

Page 4: Android Networking

Check a Device's Network Connection

Page 5: Android Networking

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).

Page 6: Android Networking

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

Page 7: Android Networking

Connecting to the Network

Page 8: Android Networking

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.

Page 9: Android Networking

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.

Page 10: Android Networking

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();….

Page 11: Android Networking

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;}

Page 12: Android Networking

Data exchange

Page 13: Android Networking

Network Architecture and Data exchange

Page 14: Android Networking

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) {...}

Page 16: Android Networking

Is there something easier?

Page 17: Android Networking

Help from the outside

Retrofithttps://square.github.io/retrofit/

Gsonhttps://github.com/google/gson

Page 18: Android Networking

Retrofit (1/3)

public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user);}

Page 19: Android Networking

Retrofit (2/3)

Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build();

GitHubService service = retrofit.create(GitHubService.class);

Page 20: Android Networking

Retrofit (3/3)

Call<List<Repo>> repos = service.listRepos("octocat");

Page 21: Android Networking

Gson

Gson gson = new Gson();String json = gson.toJson(myRepo);Repo myRepo = gson.fromJson(jsonString, Repo.class);

Page 22: Android Networking

Retrofit + Gson

Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build();

GitHubService service = retrofit.create(GitHubService.class);

Page 23: Android Networking

Retrofit + Converters

● Gson● Jackson● Moshi● Protobuf● Wire● Simple XML● Scalars

Page 24: Android Networking

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'

Page 25: Android Networking

+MatteoBonifazi@mbonifazi

Thank You!

+RobertoOrgiu@_tiwiz