gpt4 book ai didi

Android 7 ConnectivityManager requestNetwork() 行为

转载 作者:太空狗 更新时间:2023-10-29 15:50:37 29 4
gpt4 key购买 nike

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com