András Tóth‘s professional blog
banditoth.net

Hey there 👋, I’m banditoth a .NET MAUI developer from Hungary.
I write about software development with .NET technologies.

You can find me on:
LinkedIn | Github | StackOverflow | X / Twitter | Threads

  • Debug .NET MAUI Android apps with Android work profile

    An Android Work Profile is a feature that allows you to separate work apps and data from personal apps and data on the same device. This is particularly useful for maintaining privacy and security in a corporate environment. However when you are developing an app for your company, who’s got these configurations on their mobile devices, you might find yourself in a tricky solution, because VS Code simply installs the app on the workprofile and on the normal profile aswell, but only can run with debug on the normal profile without any configuration.

    Get the users of the Android device

    To list users on an Android device using ADB (Android Debug Bridge), you can use the following command:

    adb shell pm list users
    

    This command will display a list of users on the device, including their user IDs.

    For example, the output might look something like this:

    Users:
        UserInfo{0:Owner:13} running
        UserInfo{10:Work:30} running
    

    Configure the .csproj to launch the app on work profile

    Insert the following line within the <PropertyGroup> section of your .csproj file:

    <AndroidDeviceUserId>10</AndroidDeviceUserId>
    

    This attribute specifies the user ID for the Android Work Profile. The user ID 10 is commonly used for work profiles, but you should verify this for your specific setup.

    Last but not least: Hit F5 and Run your project 🙂

    Remark: This solution is only working in Visual Studio for Windows, and Visual Studio Code on mac.

    1. Resizing the screen when an Entry gets focused in .NET MAUI

      When an entry field gets focused, the software keyboard appears, potentially covering the entry field. To provide a better user experience, you need to adjust the screen layout so that the entry field remains visible.

      First, create a parent class for your views, deriving from ContentPage, and add a HaveKeyboardOffsetProperty.

      public class ViewBase : ContentPage
      {
          public static readonly BindableProperty HasKeyboardOffsetProperty =
              BindableProperty.Create(nameof(HasKeyboardOffset), typeof(bool), typeof(ViewBase), false);
      
          public bool HasKeyboardOffset
          {
              get => (bool)GetValue(HasKeyboardOffsetProperty);
              set => SetValue(HasKeyboardOffsetProperty, value);
          }
      }
      
      

      iOS Solution:

      Next, create the PageElementMapper class to handle the keyboard appearance and adjust the screen layout.

      public class PageElementMapper
      {
          private static double _contentOriginalHeight;
          private static Thickness _contentOriginalMargin;
      
          public static void Map(IElementHandler handler, IElement view)
          {
              if (view is ViewBase viewData)
              {
                  UIKeyboard.Notifications.ObserveWillShow((sender, args) =>
                  {
                      if (viewData.HasKeyboardOffset)
                      {
                          _contentOriginalHeight = viewData.Content.Height;
                          _contentOriginalMargin = viewData.Content.Margin;
                          viewData.Content.HeightRequest = _contentOriginalHeight - args.FrameEnd.Height;
                          viewData.Content.Margin = new Thickness(0, args.FrameEnd.Height, 0, 0);
                      }
                  });
      
                  UIKeyboard.Notifications.ObserveWillHide((sender, args) =>
                  {
                      if (viewData.HasKeyboardOffset)
                      {
                          viewData.Content.HeightRequest = _contentOriginalHeight;
                          viewData.Content.Margin = _contentOriginalMargin;
                      }
                  });
              }
          }
      }
      
      

      Finally, register the mapper in the MauiProgram.cs file.

      public static class MauiProgram
      {
          public static MauiApp CreateMauiApp()
          {
              var builder = MauiApp.CreateBuilder();
              builder
                  .UseMauiApp<App>()
                  .ConfigureMauiHandlers(handlers =>
                  {
                      Microsoft.Maui.Handlers.PageHandler.ElementMapper.AppendToMapping("KeyboardOffset", (handler, view) =>
                      {
                          if (view is ViewBase)
                          {
      #if IOS
                              PageElementMapper.Map(handler, view);
      #endif
                          }
                      });
                  });
      
              return builder.Build();
          }
      }
      
      

      Android solution:

      On Android, you can use a PropertyChanged method of the HasKeyboardOffset:

          private static void OnHasKeyboardOffsetPropertyChanged(BindableObject bindable, object oldValue, object newValue)
          {
      #if ANDROID
              if (bindable is ViewBase view)
              {
                  if (newValue is bool hasOffset)
                      if (hasOffset == true)
                          Microsoft.Maui.Controls.Application.Current.Dispatcher.Dispatch(() =>
                          {
                              Platform.CurrentActivity?.Window?.SetSoftInputMode(Android.Views.SoftInput.AdjustResize);
                          });
                      else
                          Microsoft.Maui.Controls.Application.Current.Dispatcher.Dispatch(() =>
                          {
                              Platform.CurrentActivity?.Window?.SetSoftInputMode(Android.Views.SoftInput.StateUnspecified);
                          });
              }
      #endif
          }
      

      Remarks

      The provided solution offers a way to manage this in .NET MAUI on iOS. However, always be open to improvements and share your solutions with the community for better practices. This might not be the best solution to do it.

    2. .NET MAUI Hide software keyboard when tapping out of an Entry on iOS

      To hide the software keyboard when the user taps outside the entry field, set the HideSoftInputOnTapped property to True in your ContentPage definition.

      <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                   x:Class="MyMauiApp.MainPage"
                   HideSoftInputOnTapped="True">
      
          <StackLayout Padding="10">
              <Entry Placeholder="Tap here to enter text" />
          </StackLayout>
      </ContentPage>
      
      

      Please note that the HideSoftInputOnTapped property might not work as expected when tapping on certain controls like ScrollView. In such cases, you might need to implement a custom behavior to handle keyboard dismissal.

    3. Resolving SQLite issues for .NET MAUI

      Recently, while working on ExampleApp, we faced two significant errors and found effective solutions for both. Here’s a detailed account of the problems and their resolutions.

      System.TypeInitializationException

      System.TypeInitializationException: The type initializer for 'SQLite.SQLiteConnection' threw an exception.
       ---> System.DllNotFoundException: e_sqlite3
      

      To resolve this error, we needed to install the latest NuGet package for SQLitePCLRaw.bundle_green. This package ensures that the necessary SQLite libraries are included in the project.

      Add the following package reference with the latest version to your project:

      <PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.10" />
      
      

      In the AppDelegate.cs file, add the following line to the CreateMauiApp method:

      protected override MauiApp CreateMauiApp()
      {
          SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
          return MauiProgram.CreateMauiApp();
      }
      

      System.ExecutionEngineException in iOS Release Mode

      System.ExecutionEngineException: Attempting to JIT compile method '(wrapper delegate-invoke) void System.Action`2<ExampleApp.Entites.LocalDatabase.VoucherLite, double>:invoke_callvirt_void_T1_T2 (ExampleApp.Entites.LocalDatabase.VoucherLite,double)' while running in aot-only mode. See https://docs.microsoft.com/xamarin/ios/internals/limitations for more information.
      

      This error occurs due to the JIT compilation attempt in AOT-only mode on iOS. The solution is to install this specific version of the sqlite-net-pcl.
      It will ONLY work with 1.7.355 or below.

      <PackageReference Include="sqlite-net-pcl" Version="1.7.335" />
      

       This solution is also applicable to Xamarin projects.

    4. Customizing .NET MAUI Map’s pin Z-Order, Rotation, and Anchor point – Android

      This post will build upon the excellent tutorial on customizing map pins in .NET MAUI by Vladislav Antonyuk, and focus on adding these specific adjustments for Android.

      • Z-order: This determines the drawing order of the pins. Pins with higher Z-order values appear on top of those with lower values.
      • Rotation: Controls the rotation angle of the pin in degrees.
      • Anchor: Defines the point on the pin image that corresponds to the pin’s location on the map. The anchor is defined in terms of a normalized coordinate system where (0, 0) is the top-left corner and (1, 1) is the bottom-right corner of the image.

      Define the Anchor Points enum, get a method to return anchor floats

      We start by defining an enum to represent the different anchor points. A helper method, GetAnchorPoint, will return the appropriate anchor coordinates based on the chosen enum value.

      public enum AnchorPointType
      {
          TopLeft,
          TopCenter,
          TopRight,
          Center,
          BottomLeft,
          BottomCenter,
          BottomRight,
          LeftCenter,
          RightCenter
      }
      

      This method returns the normalized coordinates for each anchor point, which can then be applied to the pin’s icon.

      private static (float, float) GetAnchorPoint(AnchorPointType anchor)
      {
          return anchor switch
          {
              AnchorPointType.TopLeft => (0.0f, 0.0f),
              AnchorPointType.TopCenter => (0.5f, 0.0f),
              AnchorPointType.TopRight => (1.0f, 0.0f),
              AnchorPointType.Center => (0.5f, 0.5f),
              AnchorPointType.BottomLeft => (0.0f, 1.0f),
              AnchorPointType.BottomCenter => (0.5f, 1.0f),
              AnchorPointType.BottomRight => (1.0f, 1.0f),
              AnchorPointType.LeftCenter => (0.0f, 0.5f),
              AnchorPointType.RightCenter => (1.0f, 0.5f),
              _ => (0.5f, 0.5f)  // Default to center if undefined
          };
      }
      

      Modifications to the Custom Map Handler

      Now, let’s focus on the custom map handler, where you’ll need to modify how each pin is added to the map. Following the setup from Vladislav’s tutorial, you only need to adjust the following parts in the OnMapReady method for Android:

      cp.ImageSource.LoadImage(MauiContext, result =>
      {
          if (result?.Value is BitmapDrawable bitmapDrawable)
          {
              var originalBitmap = bitmapDrawable.Bitmap;
      
              // Set the custom icon for the pin
              markerOption.SetIcon(BitmapDescriptorFactory.FromBitmap(originalBitmap));
      
              // Set the rotation of the pin
              markerOption.SetRotation((float)cp.Rotation);
      
              // Set the anchor of the pin based on the chosen AnchorPointType
              var anchor = GetAnchorPoint(cp.Anchor);
              markerOption.Anchor(anchor.Item1, anchor.Item2);
      
              // Set the Z-order to bring this pin to the top
              markerOption.InvokeZIndex(cp.ZOrder);
          }
      
          AddMarker(Map, pin, Markers, markerOption);
      });