ref https://developer.android.com/training/monitoring-device-state/connectivity-status-type
To specify the transport type of the network, such as Wi-Fi or
cellular connection, and the currently connected network's
capabilities, such as internet connection, you must configure a
network request.
Declare a NetworkRequest that describes your app’s network connection
needs. The following code creates a request for a network that is
connected to the internet and uses either a Wi-Fi or cellular
connection for the transport type.
add this in onCreate
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.build();
Configure a network callback When you register the NetworkRequest with
the ConnectivityManager, you must implement a NetworkCallback to
receive notifications about changes in the connection status and
network capabilities.
The most commonly implemented functions in the NetworkCallback include
the following:
onAvailable() indicates that the device is connected to a new network
that satisfies the capabilities and transport type requirements
specified in the NetworkRequest. onLost() indicates that the device
has lost connection to the network. onCapabilitiesChanged() indicates
that the capabilities of the network have changed. The
NetworkCapabilities object provides information about the current
capabilities of the network.
add listener
private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
}
@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
final boolean unmetered = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
}};
Register for network updates After you declare the NetworkRequest and
NetworkCallback, use the requestNetwork() or registerNetworkCallback()
functions to search for a network to connect from the device that
satisfies the NetworkRequest. The status is then reported to the
NetworkCallback.
Register in onCreate
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(ConnectivityManager.class);
connectivityManager.requestNetwork(networkRequest, networkCallback);