Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAUI Android app working fine on emulator mode but crashes after publishing Apk

I am developing an android application using Visual Studio Community Edition 2022. When I run this application on an in-built pixel emulator / on a real device through a USB connection it works as expected. But after publishing and installing signed-apk on the same device or any other android mobile phone, the app crashes soon after the splash screen.

So far I tried following solutions I found over internet.

Added following properties in my .csproj file

<PublishTrimmed>False</PublishTrimmed>
<AndroidLinkMode>None</AndroidLinkMode>
<AndroidDexTool>d8</AndroidDexTool>

<PropertyGroup>
 <AndroidPackageFormat>apk</AndroidPackageFormat>
</PropertyGroup>

<PropertyGroup>
 <AndroidEnableAssemblyCompression>false</AndroidEnableAssemblyCompression>
</PropertyGroup>

Still facing the same issue.

MauiProgram.cs

using CommunityToolkit.Maui;

namespace V2ROffline;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });
        builder.Services.AddSingleton<MainPage>();
        builder.Services.AddTransient<StockTakeWithoutFile>();
        return builder.Build();
    }
}

App.xaml.cs

namespace V2ROffline;

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new AppShell();
    }
}

App.xaml

<?xml version = "1.0" encoding = "UTF-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:V2ROffline"
             x:Class="V2ROffline.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

AppShell.xaml.cs

namespace V2ROffline;

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();
        Routing.RegisterRoute(nameof(StockTakeWithoutFile), typeof(StockTakeWithoutFile));
    }
}

AppShell.xaml

<?xml version="1.0" encoding="UTF-8" ?>
<Shell
    x:Class="V2ROffline.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:V2ROffline"
    Shell.FlyoutBehavior="Disabled">

    <ShellContent
        Title="Home"
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="MainPage" />

</Shell>

MainPage.xaml.cs

namespace V2ROffline;
using System.Text.RegularExpressions;
using V2ROffline.lib;

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();
/** Following code for checkWritePermission is not called
I believe app is crashing even before InitializeComponent() **/

        Task task = checkWritePermission();
        this.Title = Vars.TITLE + "-" + Vars.VERSION;
        TxtEmpCode.Focus();

    }
    private async Task checkWritePermission()
    {
        PermissionStatus status = await Permissions.RequestAsync<Permissions.StorageWrite>();
        status = await Permissions.RequestAsync<Permissions.StorageWrite>();
    }
    private void OnLoginClicked(object sender, EventArgs e)
    {
        string siteCode = TxtSiteCode.Text.Trim();
        string empCode = TxtEmpCode.Text.Trim();

        Regex regexSite = new Regex("^[a-zA-Z]{2}[0-9]{2}");
        Regex regexEmp = new Regex("^[a-zA-Z0-9]");

        if (!(empCode.Length >= 5 && empCode.Length <= 7 && regexEmp.IsMatch(empCode)))
        {
            DisplayAlert("Error", "Please enter valid Employee Code", "OK");
            TxtEmpCode.Focus();
            return;
        }

        if (!(siteCode.Length == 4 && regexSite.IsMatch(siteCode)))
        {
            DisplayAlert("Error", "Please enter valid Site Code", "OK");
            TxtSiteCode.Focus();
            return;
        }

        siteCode = siteCode.ToUpper();
        empCode = empCode.ToUpper();

        if (RbtnWithFile.IsChecked)
        {

        }
        else if (RbtnWithoutFile.IsChecked)
        {
            Task task = openStockTakeWithoutFile(empCode, siteCode);
        }
        else
        {
            DisplayAlert("Error", "Please select the mode of Stock Take", "OK");
            RbtnWithFile.Focus();
            return;
        }
    }

    async Task openStockTakeWithoutFile(string empCode, string siteCode)
    {
        var navigationParameter = new Dictionary<string, object>
        {
            { "EmpCode",  empCode},{ "SiteCode",  siteCode}
        };
        await Shell.Current.GoToAsync(nameof(StockTakeWithoutFile), navigationParameter);
    }

    private void OnExitClicked(object sender, EventArgs e)
    {
        App.Current.Quit();
    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="V2ROffline.MainPage">

    <ContentPage.Resources>
        <Style x:Key="InvalidEntryStyle" TargetType="Entry">
            <Setter Property="TextColor" Value="Red" />
        </Style>
        <Style x:Key="ValidEntryStyle" TargetType="Entry">
            <Setter Property="TextColor" Value="Green" />
        </Style>
    </ContentPage.Resources>

    <Grid Margin="50,50" x:Name="GridList" VerticalOptions="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="50" />
            <RowDefinition Height="50" />
            <RowDefinition Height="50" />
            <RowDefinition Height="50" />
            <RowDefinition Height="50" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions Padding="10,0">
            <ColumnDefinition Width="120"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Text="Employee Code" 
               FontAttributes="Bold"
               HeightRequest="20"
               HorizontalOptions="Start" />

        <Border Stroke="#505050"
        StrokeThickness="1"
        Background="#FFFFFF"
        Padding="10,0"
        Grid.Row="0" Grid.Column="1"
        HeightRequest="40"
        WidthRequest="170"
        HorizontalOptions="Start">
            <Border.StrokeShape>
                <RoundRectangle CornerRadius="5,5,5,5" />
            </Border.StrokeShape>
            <Entry x:Name="TxtEmpCode" 
               Placeholder="Enter employee code"
               TextTransform="Uppercase"
               MaxLength="7"
               >
                <Entry.Behaviors>
                    <toolkit:TextValidationBehavior 
                InvalidStyle="{StaticResource InvalidEntryStyle}"
                ValidStyle="{StaticResource ValidEntryStyle}"
                Flags="ValidateOnValueChanged"
                MinimumLength="5"
                MaximumLength="7" />
                </Entry.Behaviors>
            </Entry>
        </Border>
        <Label Grid.Row="1" Grid.Column="0" Text="Site Code"
               FontAttributes="Bold"
               HeightRequest="20"
               HorizontalOptions="Start" />
        <Border Stroke="#505050"
        StrokeThickness="1"
        Background="#FFFFFF"
        Padding="10,0"
        Grid.Row="1" Grid.Column="1" 
        HeightRequest="40"
        WidthRequest="170"
        HorizontalOptions="Start">
            <Border.StrokeShape>
                <RoundRectangle CornerRadius="5,5,5,5" />
            </Border.StrokeShape>
            <Entry x:Name="TxtSiteCode" 
               Placeholder="Enter site code here"
               TextTransform="Uppercase"
               MaxLength="4"
               >
                <Entry.Behaviors>
                    <toolkit:TextValidationBehavior 
                InvalidStyle="{StaticResource InvalidEntryStyle}"
                ValidStyle="{StaticResource ValidEntryStyle}"
                Flags="ValidateOnValueChanged"
                MinimumLength="4"
                MaximumLength="4" />
                </Entry.Behaviors>
            </Entry>
        </Border>
        <RadioButton x:Name="RbtnWithFile" RadioButtonGroup.GroupName="StockTake" HeightRequest="30" Content="Stock take with file" Grid.Row="2" Grid.ColumnSpan="2" />
        <RadioButton x:Name="RbtnWithoutFile" RadioButtonGroup.GroupName="StockTake" HeightRequest="30" Content="Stock take without file" Grid.Row="3" Grid.ColumnSpan="2" />
        <Button Grid.Row="4" Grid.Column="0"
            x:Name="BtnExit"
            Margin="0,10,0,0"
            Text="Exit"
            WidthRequest="120"
            Clicked="OnExitClicked"
            HorizontalOptions="Center" />
        <Button Grid.Row="4" Grid.Column="1"
            x:Name="BtnLogin"
            Margin="0,10,0,0"
            Text="Login"
            WidthRequest="120"
            Clicked="OnLoginClicked"
            HorizontalOptions="Center" />
    </Grid>

</ContentPage>
like image 591
maddy23285 Avatar asked Sep 20 '25 16:09

maddy23285


2 Answers

I am having the exact same problem.

-> Release mode working in both emulator and real devices.

-> After publishing and signing the app through VS 2022 publish option. We are not able to run the app on real devices but working as intended in emulators.

like image 160
Ebubekir Çağrı Şen Avatar answered Sep 22 '25 06:09

Ebubekir Çağrı Şen


As a developer for a small company (a little bit experienced with WPF) I decided to give a try to .NET MAUI while being asked for Android app development.

After several months of development, repetitively fighting with .NET MAUI issues I am hesitating to surrender. Unfortunately, it seems there is a lot of bugs in .NET MAUI leading to situation that development is more difficult than easy (although being promising something else). I recommended to read this blog.

Today I finally found out that although my application was working in debug mode quite fine (workaround for the styling issues had been found) switch to release mode leaded to quite different behavior (some triggers were not working, styling based on user entry not working at all).

I have just found this comment advising to focuse on Community Toolkit. It could have been the source of my issues with totally different styling as well...

I am going to update this answer with my final conclusion as soon as my investigation is done.

like image 39
hlavli Avatar answered Sep 22 '25 05:09

hlavli