如何检查是否仍连接到由 setProcessDefaultNetwork() 设置的网络
How to check if still connected to the network set by setProcessDefaultNetwork()
我有以下代码设置我的互联网连接的默认网络。
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);
}
这工作正常。但是,稍后,当我使用以下代码进行检查时:
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfoMobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
networkInfoMobile.isConnected(); // returns false!
这总是returnsfalse
。我做错了什么?
我所做的是保存 onAvailable()
回调提供的 network
。后来,我通过以下方式检查了连接:
NetworkInfo networkInfo = connMgr.getNetworkInfo(networkFromOnAvailable);
networkInfo.isConnected();
干杯!
我有以下代码设置我的互联网连接的默认网络。
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);
}
这工作正常。但是,稍后,当我使用以下代码进行检查时:
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfoMobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
networkInfoMobile.isConnected(); // returns false!
这总是returnsfalse
。我做错了什么?
我所做的是保存 onAvailable()
回调提供的 network
。后来,我通过以下方式检查了连接:
NetworkInfo networkInfo = connMgr.getNetworkInfo(networkFromOnAvailable);
networkInfo.isConnected();
干杯!