To get the status of a network, you can use the following method in your work:
public bool IsOnline() { var cm = (ConnectivityManager)GetSystemService(ConnectivityService); return cm.ActiveNetworkInfo == null ? false : cm.ActiveNetworkInfo.IsConnected; }
If I understood you correctly from this sentence: And how to refresh whole fragment after user switch-on the internet , you want to detect whenever there are any changes in the connection state, so you absolutely need to use broadcast receivers .
First of all, you should implement a broadcast receiver with a simple event called ConnectionStatusChanged as follows:
[BroadcastReceiver()] public class NetworkStatusBroadcastReceiver : BroadcastReceiver { public event EventHandler ConnectionStatusChanged; public override void OnReceive(Context context, Intent intent) { if (ConnectionStatusChanged != null) ConnectionStatusChanged(this, EventArgs.Empty); } }
Then in your activity (for example, in the OnCreate() method, it does not matter) create an instance of this receiver and register it:
var _broadcastReceiver = new NetworkStatusBroadcastReceiver(); _broadcastReceiver.ConnectionStatusChanged += OnNetworkStatusChanged; Application.Context.RegisterReceiver(_broadcastReceiver, new IntentFilter(ConnectivityManager.ConnectivityAction));
Here is the body of the event handler:
private void OnNetworkStatusChanged(object sender, EventArgs e) { if(IsOnline){ Toast.MakeText(this, "Network Activated", ToastLength.Short).Show();
To shorten the long history, NetworkStatusBroadcastReceiver receives any change in the network status of the device and calls ConnectionStatusChanged (when the user allows data traffic or WiFi connection). Then you catch this event and check the network status using the IsOnline() method. Very simple.
a.toraby
source share