Dipak
Dipak

Reputation: 1259

Internet Connectivity Listener in Xamarin.Forms

I am new in Xamarin.Forms and I want to check internet connectivity status in iOS and Android app. In fact using CrossConnectivity Plugins I am able to check internet connectivity successfully but It is not working as Listener. For example, When I open my app and internet connection is not there then it shows me message that "No internet connection" and now if I ON my mobile data then also it shows me same message. I am using below code for this:

string isConnected=CrossConnectivity.Current.IsConnected?"Connected":"No Connection";

My app is not able to listen the changing status of internet connectivity in middle something.

Upvotes: 3

Views: 3039

Answers (2)

Mr.Koçak
Mr.Koçak

Reputation: 323

I have the solution for Android but i haven't started working on ios part (better than nothing ;) First Create a broadcastReceiver

    public class Localize: BroadcastReceiver
    {
        public static Context context;

        public Localize(Context ctx)
        {
            context = ctx;
        }
        public override void OnReceive (Context context, Intent intent)
        {
            isNetworkAvailable (context);
        }

    public void isNetworkAvailable(Context context)
    {
        Boolean state = false;
        ConnectivityManager connectivity = (ConnectivityManager) 
            context.GetSystemService(Context.ConnectivityService);
        if (connectivity != null) 
        {
            NetworkInfo[] info = connectivity.GetAllNetworkInfo();
            foreach (NetworkInfo nwork in info) 
            {
                if (nwork.GetState () == NetworkInfo.State.Connected) {

                    ConnectionDetected();//Execute your fonction here
                    break;

                }
            }
        }
    }

Then register your broadcastreceiver with intent in your activity (in MainActivity for example)

IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
receiver = new Localize(this);
RegisterReceiver(receiver, filter);

This should work as long as your application is running.. If you want a service that runs even if your App is killed you should create a service and then register broadcastReceiver in your service..

CrossConnectivity.Current.IsReachable("localhost");

this also works if you download package. I haven't tested it thoroughly

Upvotes: 2

Hicham
Hicham

Reputation: 770

Using the plugin CrossConnectivity, you need to listen to changes via the event ConnectivityChanged, so in your page, or your App class, add this code to write an event handler:

CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
 {
   //your implementation
  this.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
 };

Upvotes: 4

Related Questions