gpt4 book ai didi

xamarin - 如何在 Xamarin.Android Native 中连续检查互联网连接?

转载 作者:行者123 更新时间:2023-12-02 03:03:42 35 4
gpt4 key购买 nike

我的应用程序完全基于互联网,没有它就无法运行,不幸的是,当互联网不可用或速度很慢时,我的应用程序就会停止。我尝试实现 try, catch 但它没有帮助我,因为它没有抛出任何异常,然后我认为我必须不断检查互联网连接,直到应用程序运行并停止执行任何事件并将弹出窗口设置为连接到互联网。

每当我调用其中包含以下代码的方法时,我都能获得弹出窗口,

 ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
if (networkInfo == null)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Network");
alert.SetMessage("Please turn of your Wifi or Mobile Data From Settings");
alert.SetPositiveButton("OK", (senderAlert, args) => {
Intent intent = new Intent(Android.Provider.Settings.ActionSettings);
StartActivity(intent);
});

alert.SetNegativeButton("Cancel", (senderAlert, args) => {
Toast.MakeText(this, "Cancelled!", ToastLength.Short).Show();
Finish();
});

Dialog dialog = alert.Create();
dialog.Show();

但是我无法持续检查连接,所以请有人帮助我在我的应用程序中完成此功能。

最佳答案

您需要使用 BroadcastReceiver 来监控网络变化。

    [BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "android.net.conn.CONNECTIVITY_CHANGE" })]
[Android.Runtime.Preserve(AllMembers = true)]
public class ConnectivityChangeBroadcastReceiver : BroadcastReceiver
{

public override void OnReceive(Context context, Intent intent)
{
if (intent.Action != ConnectivityManager.ConnectivityAction)
return;

//Check if is connected and raise a custom event or store
//the current in a static global variable

}
}
}

In Android 7.0, you need to remove IntentFilter from the class and register the receiver.

var receiver = new ConnectivityChangeBroadcastReceiver();
Application.Context.RegisterReceiver(receiver, new IntentFilter(ConnectivityManager.ConnectivityAction));

另一种选择是使用 ConnectivityPlugin https://github.com/jamesmontemagno/ConnectivityPlugin , 更易于使用。

CrossConnectivity.Current.ConnectivityChanged += HandleConnectivityChanged;


void HandleConnectivityChanged (object sender, ConnectivityChangedEventArgs e)
{
// You can check the network status in
//e.IsConnected
}

请注意,需要ACCESS_NETWORK_STATEACCESS_WIFI_STATE 权限。

关于xamarin - 如何在 Xamarin.Android Native 中连续检查互联网连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118129/

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