MAUI Utility Functions

MAUI utility functions

  1. Get the Android platform instance.

    1
    2
    3
    
    #if ANDROID
        var activity = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity;
    #endif
    
  2. Get the Android platform context.

    1
    2
    3
    
    var context = Android.App.Application.Context;
    // or
    context = Platform.AppContext;
    
  3. Check the Android build version.

    1
    2
    3
    
    if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.R)
    {
    }
    
  4. When setting parameters for cross-platform scenarios, ensure parameters for all platforms are set to avoid warnings.

    1
    2
    3
    4
    
    <!-- No warning -->
    <Setter Property="FontSize" Value="{OnPlatform Android=16,WinUI=15}"/> 
    <!-- Warning -->
    <Setter Property="FontSize" Value="{OnPlatform Android=16}"/> 
    
  5. Releasing in APK format on Android may cause issues; switch back to AAB format.
    If the project references third-party .so files with special characters or irregular casing in their names, it may cause the released app to malfunction. Rename the files to be short and standardized.

    1
    2
    3
    
    <!--<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net8.0-android|AnyCPU'">
      <AndroidPackageFormat>apk</AndroidPackageFormat>
    </PropertyGroup>-->
    
  6. For Android build properties in Visual Studio, refer to this link.

  7. Specify the Android target SDK version by modifying the AndroidManifest.xml file.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true" android:noHistory="true"></application>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
        <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
        <uses-permission android:name="android.permission.READ_SETTINGS"/>
        <uses-permission android:name="android.permission.READ_SECURE_SETTINGS"/>
        <!-- Add target version -->
        <uses-sdk android:targetSdkVersion="29" /> 
    </manifest>
    
  8. Get all settings strings on the Android platform.

    1
    2
    3
    4
    
    var list = Intent.Class.GetFields();
    // ACTION_AIRPLANE_MODE_CHANGED
    // ACTION_ALARM_CHANGED
    // EXTRA_ALARM_COUNT
    
  9. Modify Android platform system settings. Refer to settings.

    1
    2
    
    // Modify the system property persist.sys.language to zh_CN
    Settings.System.putString(getContentResolver(), Settings.System.LANGUAGE, "zh_CN");
    
  10. Reboot or shutdown (requires root permissions).

    1
    2
    3
    4
    5
    
    Java.Lang.Runtime.GetRuntime().Exec("su");
    // Reboot
    Java.Lang.Runtime.GetRuntime().Exec("reboot");
    // Shutdown
    Java.Lang.Runtime.GetRuntime().Exec("reboot -p");
    
  11. Close the current app.

    1
    
    Application.Current.Quit();
    
  12. Request system permissions. For detailed permissions, refer to the official documentation.

    1
    2
    3
    4
    5
    6
    7
    8
    
    var state = await Permissions.RequestAsync<Permissions.Bluetooth>();
    if (state != PermissionStatus.Granted)
    {
        if (Application.Current != null && Application.Current.MainPage != null)
        {
            await Application.Current.MainPage.DisplayAlert($"Warning", $"Missing required permissions, the app will not function properly!", $"OK");
        }
    }
    
  13. Forcefully close already running processes.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    Process process = Process.GetCurrentProcess();
    var pro = Process.GetProcessesByName(process.ProcessName);
    foreach (var p in pro)
    {
        if (p.Id != process.Id)
        {
            if (p.MainModule.FileName == process.MainModule.FileName)
            {
                p.Kill();
            }
        }
    }
    
  14. Get the IP address.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    var upAndNotLoopbackNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces().Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback
                                                                                              && n.OperationalStatus == OperationalStatus.Up);
    
    foreach (var networkInterface in upAndNotLoopbackNetworkInterfaces)
    {
        var iPInterfaceProperties = networkInterface.GetIPProperties();
    
        var unicastIpAddressInformation = iPInterfaceProperties.UnicastAddresses.FirstOrDefault(u => u.Address.AddressFamily == AddressFamily.InterNetwork);
        if (unicastIpAddressInformation != null)
        {
            return unicastIpAddressInformation.Address.ToString();
        }                
    }
    
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy