I'm working on an app which only performs some secure operations when the app is connected to a mobile data network. I'm trying to get the app to force all of it's network traffic over a specific network so I am looking at this api call added in level 21: http://developer.android.com/reference/android/net/ConnectivityManager.html#setProcessDefaultNetwork(android.net.Network)
Network[] networks = cm.getAllNetworks();
for (int i = 0; i < networks.length; i++) {
NetworkInfo netInfo = cm.getNetworkInfo(networks[i]);
if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
foundMobile = true;
Log.d("ANDREW", "Found potential network: setting default...");
result = ConnectivityManager.setProcessDefaultNetwork(networks[i]);
Log.d("ANDREW", "Result: " + result);
}
if (result) {
Log.d("ANDREW", "Success! Restricted to: " + netInfo.toString());
break;
}
}
Basically I'm getting all the supported networks for the device, checking all of them and seeing if any of them are mobile networks, and then attempting to set the default network. It does find the mobile network but it never manages to set it as the default network. The result is false, and future results of:
Network defProcNetwork = ConnectivityManager.getProcessDefaultNetwork();
are also null.
I have also tried an alternative method, incase the network just isn't available based on another SO answer I saw:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
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) {
Log.d("ANDREW", "Network is available!");
boolean result = ConnectivityManager.setProcessDefaultNetwork(network);
Log.d("ANDREW", "RESULT: " + result);
if (ConnectivityManager.getProcessDefaultNetwork() != null) {
Log.d("ANDREW", "Successfully set default network ");
}
}
};
NetworkRequest networkRequest = builder.build();
connectivityManager.requestNetwork(networkRequest, networkCallback);
connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
I get the isAvailable callback, but it still can't set the default network.
There are no log messages to work with, I've even looked at the native code and there is just nothing there to indicate what is wrong. The SDK doesn't describe any extra steps that I can see so my question is, why is this always returning false and what exactly is a developer supposed to do to get this to work? I've tried this on both a Nexus 5 and a Nexus 6.