xamarin 网络信息类型已过时:“已弃用”

zed5wv10  于 2023-02-27  发布在  其他
关注(0)|答案(3)|浏览(187)

例如,我有这个方法:

public static bool IsConnectedMobile
        {
            get
            {
                var info = ConnectivityManagers.ActiveNetworkInfo;
                return info != null && info.IsConnected && info.Type == ConnectivityType.Mobile;
            }
        }

我在这里得到一个错误:信息类型==连接类型.移动的;

我的问题是,我能找到一个替代方案吗?(不使用其他库)

ljsrvy3e

ljsrvy3e1#

ActiveNetworkInfo您需要从GetSystemService获取它只需使用此代码

ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);
NetworkInfo activeNetwork = cm.ActiveNetworkInfo;
if (activeNetwork != null)
{ 
   //connected to the internet
}
 else
{
  //not connected to the internet
}

&有关详细信息,请通过this线程

zbwhf8kr

zbwhf8kr2#

此功能是平台特定的。基本上,您可以使用以下代码检查网络连接状态:

var cm = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
bool isConnected = cm.ActiveNetworkInfo.IsConnected;

应该很简单。
谢谢。

a6b3iqyw

a6b3iqyw3#

自API29 Android版本10.0起,因为NetworkInfo已弃用

#if __ANDROID_29__
           // Code to execute on Android 10 (API level 29) or higher
            ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);
            var activeNetwork = cm.ActiveNetwork;
            if (activeNetwork != null)
            {
                //connected to the internet
                Toast.MakeText(this, "connected to the internet", ToastLength.Long).Show();

                NetworkCapabilities networkCapabilities = cm.GetNetworkCapabilities(cm.ActiveNetwork);
                if (networkCapabilities != null && networkCapabilities.HasTransport(TransportType.Cellular))
                {
                    int networkSpeed = networkCapabilities.LinkDownstreamBandwidthKbps;

                    if (networkSpeed < 1000)
                    {
                        // Internet connection is slow
                        Toast.MakeText(this, "Internet connection is slow", ToastLength.Long).Show();
                    }
                }
            }
            else
            {
                //not connected to the internet
                Toast.MakeText(this, "not connected to the internet", ToastLength.Long).Show();
             
            }
#endif

相关问题