I have the following code that sets the default network of my internet connection.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
NetworkCallback networkCallback = new NetworkCallback() {
@Override
public void onAvailable(Network network) {
boolean result = ConnectivityManager.setProcessDefaultNetwork(network);
Log.d(TAG, "success? " + result);
}
};
NetworkRequest networkRequest = builder.build();
connMgr.requestNetwork(networkRequest, networkCallback);
connMgr.registerNetworkCallback(networkRequest, networkCallback);
}
This works properly. However, later on, when I check using the following code:
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfoMobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
networkInfoMobile.isConnected(); // returns false!
This always returns false
. What am I doing wrong?
What I did is I saved the network
provided by onAvailable()
callback. Then later, I checked the connectivity thru:
NetworkInfo networkInfo = connMgr.getNetworkInfo(networkFromOnAvailable);
networkInfo.isConnected();
Cheers!