【问题标题】:Android 7 ConnectivityManager requestNetwork() behaviourAndroid 7 ConnectivityManager requestNetwork() 行为
【发布时间】:2017-04-05 13:00:34
【问题描述】:

我正在使用一些代码来检测移动数据和蜂窝网络是否可用,如下所示:

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在这方面有什么变化吗?我至少希望调用其中一个回调,但没有任何返回。

【问题讨论】:

    标签: android android-networking


    【解决方案1】:

    我找到了答案。我只需要像这样将 NET_CAPABILITY_INTERNET 添加到请求生成器中:

    request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2019-09-13
      • 2020-12-14
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多