作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用一些代码来检测移动数据和蜂窝网络是否可用,如下所示:
final ConnectivityManager connection_manager =
(ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean mobileDataEnabled = false;
try {
Class cmClass = Class.forName(connection_manager.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(connection_manager);
} catch (Exception e) {
}
if(mobileDataEnabled == true) {
Log.d(TAG, "mobileDataEnabled == true");
} else {
Log.d(TAG, "mobileDataEnabled == false");
}
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
connection_manager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback()
{
@Override
public void onAvailable(Network network)
{Log.d(TAG, "requestNetwork onAvailable()");}
@Override
public void onCapabilitiesChanged (Network network, NetworkCapabilities networkCapabilities)
{Log.d(TAG, "requestNetwork onCapabilitiesChanged()");}
@Override
public void onLinkPropertiesChanged (Network network, LinkProperties linkProperties)
{Log.d(TAG, "requestNetwork onLinkPropertiesChanged()");}
@Override
public void onLosing (Network network, int maxMsToLive)
{Log.d(TAG, "requestNetwork onLosing()");}
@Override
public void onLost (Network network)
{Log.d(TAG, "requestNetwork onLost()");}
});
到目前为止,它一直正常工作,如果可以使用移动数据,则会触发 onAvailable() 回调。但是,我刚刚在 android 7 设备上进行了尝试,虽然 mobileDataEnabled 被设置为 true,表明网络可用,但 requestNetwork() 回调都没有被触发。
有谁知道 android 7 在这方面有什么变化吗?我至少希望调用其中一个回调,但没有任何返回。
最佳答案
我找到了答案。我只需要像这样将 NET_CAPABILITY_INTERNET 添加到请求构建器中:
request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
关于Android 7 ConnectivityManager requestNetwork() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232006/
我正在使用一些代码来检测移动数据和蜂窝网络是否可用,如下所示: final ConnectivityManager connection_manager = (Conn
通过主线程调用 ConnectivityManager 的 requestNetwork() 接口(interface)是否安全,或者它暂停了 ANR 错误的威胁? 最佳答案 是的。这是一个异步操作。
我正在尝试使用 ConnectivityManager.requestNetwork(NetworkRequest, ConnectivityManager.NetworkCallback) 获取新的
我是一名优秀的程序员,十分优秀!