Showing posts with label InternetConnectivity. Show all posts
Showing posts with label InternetConnectivity. Show all posts

Thursday, May 11, 2023

Daily#6. Understanding and Using NetworkCallback in Android

The NetworkCallback class plays a crucial role in handling network changes in Android. It allows apps to monitor the network's state and perform actions accordingly. It has different types such as DefaultNetworkCallback, Request type NetworkCallback and Listen type NetworkCallback.

Default Network

 In Android, the "default network" refers to the network that is currently being used for internet traffic. Most of the time, it is the network that your device is connected to for accessing the internet, either via Wi-Fi or mobile data.

 The default network can change based on factors like network availability, signal strength, and user preferences. For instance, if you're connected to both Wi-Fi and mobile data, Android generally defaults to using Wi-Fi because it's typically faster and doesn't incur data charges. However, if the Wi-Fi signal becomes weak or disconnects, Android will automatically switch the default network to mobile data (if available) to maintain internet connectivity.

 So, when we talk about a "DefaultNetworkCallback" in Android, we are referring to a callback method that will be invoked when the device's default network changes, such as when the device connects to or disconnects from a network. This allows your app to respond to changes in the device's internet connectivity, providing opportunities for improving user experience and app performance.

 DefaultNetworkCallback is a convenience callback that apps can use to handle the availability of the default network:
final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // Handle the availability of the default network
    }

    @Override
    public void onLost(Network network) {
        // Handle the loss of the default network
    }
};

connectivityManager.registerDefaultNetworkCallback(networkCallback);

Listen vs Request NetworkCallback
When it comes to network requests, Android's ConnectivityManager offers two types of NetworkCallback: Request type and Listen type.
Here's a more detailed comparison:

Request type NetworkCallback:
When you call requestNetwork(), Android tries to satisfy your NetworkRequest. It essentially means "I need a network with these capabilities". Android will then attempt to switch to or bring up a network that meets the request, if one is not already available.

This method should be used when your app cannot accomplish its task without a network that has the capabilities defined by the NetworkRequest.

In simpler terms, a Request type NetworkCallback is an active request, Android will take action to satisfy your request.
 
NetworkRequest request = new NetworkRequest.Builder()
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .build();

connectivityManager.requestNetwork(request, networkCallback);

Listen type NetworkCallback:
When you call registerNetworkCallback(), you're saying "Let me know when a network of this nature comes up". However, unlike requestNetwork(), this method does not cause any sort of network switchover or any attempt to satisfy the NetworkRequest.

Use this method when your app can alternatively use whichever network is available or when you just want to know when a network of interest is available.
NetworkRequest request = new NetworkRequest.Builder()
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .build();

connectivityManager.registerNetworkCallback(request, networkCallback);

Please, refer to Daily#2 for implementing NetworkCallback. 

 In summary, the key difference between the two is that requestNetwork() is an active request where Android will try to satisfy your network needs, while registerNetworkCallback() is more of a passive listener and won't cause Android to take any action other than notifying you of network changes.

Remember: To use these APIs, you need to add the ACCESS_NETWORK_STATE and CHANGE_NETWORK_STATE permissions to your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />


Wednesday, May 10, 2023

Daily#2. Handling Network Connectivity Issues in Android Apps

 When developing an Android app, it's important to ensure your app can handle network connectivity issues, especially when switching between Wi-Fi and mobile data. Android provides APIs to monitor network connectivity and report issues to help you manage your app's behavior in different network situations.
  1. Register a `ConnectivityManager.NetworkCallback` to monitor network changes:
    private ConnectivityManager connectivityManager;
    private ConnectivityManager.NetworkCallback networkCallback;
    
    private void registerNetworkCallback(Context context) {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                // Handle network connection established
            }
    
            @Override
            public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities nc) {
                // onCapabilitiesChanged
                boolean valid = nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
            }
    
            @Override
            public void onLost(Network network) {
                // Handle network connection lost
            }
        };
    
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        connectivityManager.registerNetworkCallback(builder.build(), networkCallback);
    }     
  2. Don't forget to unregister the `NetworkCallback` when it's no longer needed, such as in your Activity's `onDestroy()` method:
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connectivityManager != null && networkCallback != null) {
            connectivityManager.unregisterNetworkCallback(networkCallback);
        }
    }
  3. Report network connectivity problems using ConnectivityManager.reportNetworkConnectivity():
    private void reportNetworkConnectivity(Context context, boolean hasProblem) {
        Network activeNetwork = connectivityManager.getActiveNetwork();
        if (activeNetwork != null) {
            connectivityManager.reportNetworkConnectivity(activeNetwork, hasProblem);
        }
    }   

With these code snippets, your app can monitor and respond to network connectivity changes and provide a better user experience by handling Wi-Fi and mobile data transitions more gracefully. Remember to request the ACCESS_NETWORK_STATE permission in your AndroidManifest.xml file to use the ConnectivityManager APIs:
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Learning Journey #6: Brief Exploration of Databases and its Management Systems

  Welcome to the "Learning Journey" series. This space is my personal archive where I share insights and discoveries from my explo...