The document discusses various topics related to networking and managing data from the web for Android applications. It covers checking a device's network connectivity, performing secure network communication, choosing an HTTP client like HttpURLConnection, performing network operations on a background thread, and parsing JSON responses. It also introduces libraries like Retrofit and Gson that can simplify making network requests and parsing responses.
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.