List of available Wifi devices
You can get the available WIFI Scan results by
List<ScanResult> mScanResults = mWifiManager.getScanResults();
Then iterating over mScanResults
and getting SSID using results.SSID
. Also if you are interested to get the best network you can use WifiManager.compareSignalLevel(int rssiA, int rssiB)
for comparing two networks.
ScanResult bestResult = null;
for(ScanResult results : mScanResults){
Log.d("result",results.SSID);
if(bestResult == null || WifiManager.compareSignalLevel(bestResult.level,
results.level) < 0){
bestResult = results;
}
}
String message = String.format("%s networks found. %s is the strongest.",
mScanResults.size(), bestResult.SSID);
Log.d("best network",message);
You can download complete demo from my repository
.
How to get list of nearby WiFi Networks in Android Xamarin.Forms?
About getting Wifi list in Xamarin.forms, I do one sample using DependencyService.
Creating interface in PCL:
public interface IWifi
{
Task<IEnumerable<string>> GetAvailableNetworksAsync();
}
Implementing the interface on Android platform
[assembly: Xamarin.Forms.Dependency(typeof(ListWifi.Droid.Wifi))]
namespace ListWifi.Droid
{
[Activity(Label = "ListWifi", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
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);
}
}
public class Wifi : IWifi
{
private Context context = null;
public Wifi()
{
this.context = Android.App.Application.Context;
}
public async Task<IEnumerable<string>> GetAvailableNetworksAsync()
{
IEnumerable<string> availableNetworks = null;
// Get a handle to the Wifi
var wifiMgr = (WifiManager)context.GetSystemService(Context.WifiService);
var wifiReceiver = new WifiReceiver(wifiMgr);
await Task.Run(() =>
{
// Start a scan and register the Broadcast receiver to get the list of Wifi Networks
context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
availableNetworks = wifiReceiver.Scan();
});
return availableNetworks;
}
[BroadcastReceiver(Enabled = true, Exported = false)]
class WifiReceiver : BroadcastReceiver
{
private WifiManager wifi;
private List<string> wifiNetworks;
private AutoResetEvent receiverARE;
private Timer tmr;
private const int TIMEOUT_MILLIS = 20000; // 20 seconds timeout
public WifiReceiver()
{
}
public WifiReceiver(WifiManager wifi)
{
this.wifi = wifi;
wifiNetworks = new List<string>();
receiverARE = new AutoResetEvent(false);
}
public IEnumerable<string> Scan()
{
tmr = new Timer(Timeout, null, TIMEOUT_MILLIS, System.Threading.Timeout.Infinite);
wifi.StartScan();
receiverARE.WaitOne();
return wifiNetworks;
}
public override void OnReceive(Context context, Intent intent)
{
IList<ScanResult> scanwifinetworks = wifi.ScanResults;
foreach (ScanResult wifinetwork in scanwifinetworks)
{
wifiNetworks.Add(wifinetwork.Ssid);
}
receiverARE.Set();
}
private void Timeout(object sender)
{
// NOTE release scan, which we are using now, or we throw an error?
receiverARE.Set();
}
}
}
}
MainPage.xaml:
<StackLayout>
<ListView x:Name="wifilist">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding .}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button
x:Name="btn1"
Clicked="btn1_Clicked"
Text="get wifi list" />
</StackLayout>
Mainpage.cs:
private async void btn1_Clicked(object sender, EventArgs e)
{
_wifiService = await DependencyService.Get<IWifi>().GetAvailableNetworksAsync();
wifilist.ItemsSource = _wifiService;
}
If you want to refresh wifi list in some time, you can use Timer to do this:
private async void btn1_Clicked(object sender, EventArgs e)
{
//_wifiService = await DependencyService.Get<IWifi>().GetAvailableNetworksAsync();
//wifilist.ItemsSource = _wifiService;
Device.StartTimer(new TimeSpan(0, 0, 60), () =>
{
// do something every 60 seconds
Device.BeginInvokeOnMainThread(async() =>
{
_wifiService = null;
_wifiService = await DependencyService.Get<IWifi>().GetAvailableNetworksAsync();
wifilist.ItemsSource = _wifiService;
});
return true; // runs again, or false to stop
});
}
Note: for WiFi Scanning, please permission.
Related Topics
How to Stop Asynctask Thread in Android
Forcing the Soft Keyboard Open
How to Implement a Listview Without Listactivity? (Use Only Activity)
How to Add "Go Back" Function in Webview Inside Fragment
Getlastknownlocation Always Return Null After I Re-Install the APK File via Eclipse
How to Get Cell Service Signal Strength in Android
Android Studio Adb Syntax Error: ")" Unexpected
Multi Selection Spinner in Android Without Alertdialog
Pass Arraylist from One Activity to Other
How to Create Custom Baseadapter for Autocompletetextview
Android - Getting Audio to Play Through Earpiece
How to 'Gettopactivity' Name or Get Currently Running Application Package Name in Lollipop
Import .CSV File to SQLite in Android
Creating a Directory in /Sdcard Fails
How to Find MAC Address of an Android Device Programmatically
What Is the Benefit of Viewholder Pattern in Android
Android Take Screen Shot Programmatically
Place 2 Textview Beside Each Other with 2Nd Textview Always Visible