Continuous checking of WiFi connection status

AMER SAID 396 Reputation points
2022-03-10T17:55:53.427+00:00

hi

Use the following Broadcast to see the status of your Wi-Fi connection through Toast message.
I want instead of the message showing the result of calling through TextView to appear in the specified interface Activity

//

        class Class1
        {

            [BroadcastReceiver]
            [IntentFilter(new string[] { WifiManager.NetworkStateChangedAction, WifiManager.WifiStateChangedAction })]
            public class NetworkBroadcastReceiver : BroadcastReceiver
            {
                readonly WifiManager wifiManager;
                public static string LastSSID;

                public NetworkBroadcastReceiver(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer)
                {
                    wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
                }

                public NetworkBroadcastReceiver()
                {
                    wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
                }

                [Obsolete]
                public override void OnReceive(Context context, Intent intent)
                {
                    string currentSSID = null;
                    if (WifiManager.NetworkStateChangedAction == intent.Action)
                    {
                        var netInfo = (NetworkInfo)intent.GetParcelableExtra(WifiManager.ExtraNetworkInfo);
                        var netInfoDetailed = netInfo.GetDetailedState();
                        if (netInfo.IsConnected || netInfoDetailed == NetworkInfo.DetailedState.Connected)
                        {
                            currentSSID = wifiManager.ConnectionInfo.SSID;
                        }
                        else if (!netInfo.IsConnected)
                        {
                            currentSSID = null;
                        }
                    }
                    if (WifiManager.WifiStateChangedAction == intent.Action)
                    {
                        currentSSID = GetCurrentSSID();
                    }
                    if (LastSSID != currentSSID)
                    {

                        Toast.MakeText(context, $"Wireless SSID changed, from:{LastSSID} to:{currentSSID}", ToastLength.Long).Show();
                        LastSSID = currentSSID;
                    }
                }

                public static string GetCurrentSSID()
                {
                    var wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
                    if (wifiManager.ConnectionInfo.SupplicantState == SupplicantState.Completed)
                    {
                        return wifiManager.ConnectionInfo.SSID;
                    }
                    return null;
                }
            }
        }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,326 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 72,336 Reputation points Microsoft Vendor
    2022-03-16T02:37:02.423+00:00

    I have not dealt with the Broadcast before. Can you modify my code?
    Or put a simple completed example.

    Firstly, you can create Xamarin.Android project. Then open your MainActivity.cs. I put the BroadcastReceiver to the MainAcitivity blew for tesing in same namespace.

    using Android.App;
    using Android.Content;
    using Android.Net;
    using Android.Net.Wifi;
    using Android.OS;
    using Android.Runtime;
    using Android.Widget;
    using AndroidX.AppCompat.App;
    using System;
    using Xamarin.Essentials;
    
    namespace XAndroidBroadCastDemo
    {
      [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
        public class MainActivity : AppCompatActivity, NetworkBroadcastReceiver.ScanWiFI
        {
            TextView textView;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    
                SetContentView(Resource.Layout.activity_main);
    
               //request location permission at the runtime.
    
                var status =  Permissions.RequestAsync<Permissions.LocationWhenInUse>();
    
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.AddAction(WifiManager.NetworkStateChangedAction);
                intentFilter.AddAction(WifiManager.WifiStateChangedAction);
                NetworkBroadcastReceiver receiver = new NetworkBroadcastReceiver();
                RegisterReceiver(receiver, intentFilter);
    
                //register this interface as well
                receiver.SetWifiScan(this);
                textView = FindViewById<TextView>(Resource.Id.textView1);
            }
    
            //set wifi information here If wifi changed.
            public void WiFiInformation(string info)
            {
    
                textView.Text = info;
            }
    
            public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
            {
                Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    
                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    
    
    
    
        [BroadcastReceiver]
        [IntentFilter(new string[] { WifiManager.NetworkStateChangedAction, WifiManager.WifiStateChangedAction })]
        public class NetworkBroadcastReceiver : BroadcastReceiver
        {
            readonly WifiManager wifiManager;
            public static string LastSSID;
    
            public NetworkBroadcastReceiver(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer)
            {
                wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
            }
    
            public NetworkBroadcastReceiver()
            {
                wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
            }
    
    
            public interface ScanWiFI
            {
                public void WiFiInformation(string info);
            }
            private ScanWiFI scanwifi;
            public void SetWifiScan(ScanWiFI scanWiFI)
            {
                this.scanwifi = scanWiFI;
            }
            [Obsolete]
            public override void OnReceive(Context context, Intent intent)
            {
                string currentSSID = null;
                if (WifiManager.NetworkStateChangedAction == intent.Action)
                {
                    var netInfo = (NetworkInfo)intent.GetParcelableExtra(WifiManager.ExtraNetworkInfo);
                    var netInfoDetailed = netInfo.GetDetailedState();
                    if (netInfo.IsConnected || netInfoDetailed == NetworkInfo.DetailedState.Connected)
                    {
                        currentSSID = wifiManager.ConnectionInfo.SSID;
                    }
                    else if (!netInfo.IsConnected)
                    {
                        currentSSID = null;
                    }
                }
                if (WifiManager.WifiStateChangedAction == intent.Action)
                {
                    currentSSID = GetCurrentSSID();
                }
                if (LastSSID != currentSSID)
                {
                    scanwifi.WiFiInformation($"Wireless SSID changed, from:{LastSSID} to:{currentSSID}");
                    //Toast.MakeText(context, $"Wireless SSID changed, from:{LastSSID} to:{currentSSID}", ToastLength.Long).Show();
                    LastSSID = currentSSID;
                }
            }
    
            public static string GetCurrentSSID()
            {
                var wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
    
                if (wifiManager.ConnectionInfo.SupplicantState == SupplicantState.Completed)
                {
                    return wifiManager.ConnectionInfo.SSID;
                }
                return null;
            }
        }
    }
    

    And Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from wifiManager.ConnectionInfo.SSID;. Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

    please open your AndroidManifest.xml add following permission in <manifest> tag.

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 72,336 Reputation points Microsoft Vendor
    2022-03-11T03:32:03.24+00:00

    Hello,​

    If you want to transfer data from BroadcastReceiver to Activity, you can create a interface, use interface call back to achieve it.

    Firstly, we can add a interface called ScanWiFI, add WiFiInformation method to this ScanWiFI interface.

    And set method called SetWifiScan(ScanWiFI scanWiFI) to the NetworkBroadcastReceiver.cs(Note: I use ... to omit existing code) like following code.

    When we get the currentSSID information in the OnReceive method, we can use scanwifi.WiFiInformation($"Wireless SSID changed, from:{LastSSID} to:{currentSSID}"); to send it to Activity.

       [BroadcastReceiver]  
           [IntentFilter(new string[] { WifiManager.NetworkStateChangedAction, WifiManager.WifiStateChangedAction })]  
           public class NetworkBroadcastReceiver : BroadcastReceiver  
           {  
               
       ...  
               public interface ScanWiFI  
               {  
                   public void WiFiInformation(string info);  
               }  
               private ScanWiFI scanwifi;  
               public void SetWifiScan(ScanWiFI scanWiFI)  
               {  
                   this.scanwifi = scanWiFI;  
               }  
         
               [Obsolete]  
               public override void OnReceive(Context context, Intent intent)  
               {  
                  ...  
                   if (LastSSID != currentSSID)  
                   {  
                       scanwifi.WiFiInformation($"Wireless SSID changed, from:{LastSSID} to:{currentSSID}");  
                      // Toast.MakeText(context, $"Wireless SSID changed, from:{LastSSID} to:{currentSSID}", ToastLength.Long).Show();  
                       LastSSID = currentSSID;  
                   }  
               }  
       ...  
    

    Then we can open the Acitivity to achieve ScanWiFI interface, and we need to achieve this WiFiInformation(string info) method, do not forget to register this interface as well, we can get the wifi information in the WiFiInformation directly

       public class MainActivity : AppCompatActivity, NetworkBroadcastReceiver.ScanWiFI  
           {  
               TextView textView;  
               protected override void OnCreate(Bundle savedInstanceState)  
               {  
       ...  
                   IntentFilter intentFilter = new IntentFilter();  
                   intentFilter.AddAction(WifiManager.NetworkStateChangedAction);  
                   intentFilter.AddAction(WifiManager.WifiStateChangedAction);  
                   NetworkBroadcastReceiver receiver = new NetworkBroadcastReceiver();  
                   RegisterReceiver(receiver, intentFilter);  
         
                   //register this interface as well  
                   receiver.SetWifiScan(this);  
         
                   textView = FindViewById<TextView>(Resource.Id.textView1);  
       ...  
             }  
         
         
            //set wifi information here If wifi changed.  
               public void WiFiInformation(string info)  
               {  
                 
                   textView.Text = info;     
               }  
       }  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.