gpt4 book ai didi

Android getAllNetworkInfo() 已弃用。什么是替代方案?

转载 作者:IT老高 更新时间:2023-10-28 22:06:06 26 4
gpt4 key购买 nike

我想使用 ConnectivityManager 提供 getAllNetworkInfo() 方法来检查 Android 中的网络可用性。此方法在 API 级别 23 中已弃用。开发人员文档建议改用 getAllNetworks()。我尝试过,但无法从旧代码中获得确切的功能。请有人指导我如何使用 getAllNetworks() 方法?

 public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
@SuppressWarnings("deprecation")
NetworkInfo[] info = connectivity.getAllNetworkInfo();
//use getAllNetworks() instead
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}

最佳答案

当我更新已弃用的代码但仍想支持向后 Api 时。我用这个:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.WANTED API VERSION){
//code
}else{
//code
}

通过这种方式,每个设备都为其使用适当的代码。示例:

public class ConnectionDetector {

private Context mContext;

public ConnectionDetector(Context context) {
this.mContext = context;
}
/**
* Checking for all possible internet providers
* **/
public boolean isConnectingToInternet() {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
}else {
if (connectivityManager != null) {
//noinspection deprecation
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
LogUtils.d("Network",
"NETWORKNAME: " + anInfo.getTypeName());
return true;
}
}
}
}
}
Toast.makeText(mContext,mContext.getString(R.string.please_connect_to_internet),Toast.LENGTH_SHORT).show();
return false;
}
}

关于Android getAllNetworkInfo() 已弃用。什么是替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32242384/

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