Search code examples
android.netmauiwifi

How to programatically open the Internet settings page on an Android device


Using .NET MAUI, I want to programmatically open this page: In an Android device, open Settings > Connections > WiFi. This shows the currently connected network and available networks. It looks slightly different for different Android versions, but it basically looks like this (sorry about low-quality image):
enter image description here

When the user opens this page, they will select a local WiFi network that was created earlier in the program.

I will probably have to invoke platform-specific code to do this, which is fine, I just don't know what Android-specific code to use.

I've been given this answer before, to use AppInfo.Current.ShowSettingsUI(). This is not what I need, as this opens the application's settings page. I want to programatically open the aforementioned Android settings page.

What have I tried?

I've successfully done the tutorial that uses Android code to do something simple, so I think that if I find the correct Android API to call, then hopefully I will be ok (sadly, my Java in nonexistent, so I'm pretty lost in the Android-Dev page). I'm not sure what permissions I'll need, but I can certainly set them when the time comes.

EDIT: success, here's what I did
In a ViewModel, I have a plain old method that I get to through pressing a button:

namespace SandboxProject.ViewModel;
public partial class OpenSettingsAttemptsPageViewModel : ObservableObject
{
    [RelayCommand]
    private async Task ActionWifiSettings()
    {
        // put code here
    }
}

Next, I basically just added the line of code that was suggested to me below:

    [RelayCommand]
    private async Task ActionWifiSettings()
    {
        Platform.CurrentActivity?.StartActivity(new Intent(Settings.ActionWifiSettings));
    }

Finally, I cleaned up the code with some conditional statements, some using statements, and a try/catch:

#if ANDROID
using Android.Content;
using Android.Provider;
#endif

namespace SandboxProject.ViewModel;
public partial class OpenSettingsAttemptsPageViewModel : ObservableObject
{
    [RelayCommand]
    private async Task ActionWifiSettings()
    {
#if ANDROID
        try
        {
            Platform.CurrentActivity?.StartActivity(new Intent(Settings.ActionWifiSettings));
        }
        catch (Exception ex)
        {
            await App.Current!.MainPage!.DisplayAlert("Exception", ex.Message, "OK");
        }
#endif
    }
}

I ran the code on several emulators using different versions of Android (nothing really old) and my own physical phone, and it worked great. I didn't mess with any of the permissions... I left AndroidManifest.xml as default.


Solution

  • You can use Settings provider to start an activity with the Intent: ACTION_WIFI_SETTINGS

    #if ANDROID
      Platform.CurrentActivity?.StartActivity(new Intent(Settings.ActionWifiSettings));
    #endif