我试图暂时强制设备使用移动数据。我正在使用ConnectivityManager.requestNetwork()
,
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
connectivityManager.requestNetwork(request.build(), newRequestTransportCallback(connectivityManager),
(int) TimeUnit.SECONDS.toMillis(10));
newRequestTransportCallback()
返回的地方,
new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.d(TAG,"Network available: " + network + ", binding...");
if (cm.bindProcessToNetwork(network)) {
Log.d(TAG,"Bind successful to network: " + network);
} else {
Log.w(TAG,"Bind failed to network: " + network);
}
}
@Override
public void onUnavailable() {
Log.w(TAG,"Network not available");
}
};
我可以从我的日志语句中看到请求和绑定成功。但是,当我随后致电ConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
时,它告诉我网络已断开连接(并且我已尝试轮询以查看更新网络信息是否有一些延迟,但也没有成功)。
不确定我在这里做错了什么。 感谢。