.NET MAUI Android发布版APK崩溃:Android Activity不能为空
.NET MAUI Release版APK启动崩溃:Android Activity can't be null
问题现象
Debug模式下应用运行正常,但打包为Release版APK后启动即崩溃,抛出异常:
android.runtime.JavaProxyThrowable: System.InvalidOperationException: Android Activity can't be null.
崩溃日志
Time Device Name Type PID Tag Message 12-15 13:53:50.503 pixel_5_-_api_33 Info 20162 MonoDroid android.runtime.JavaProxyThrowable: System.InvalidOperationException: Android Activity can't be null. at CommunityToolkit.Maui.Core.Platform.StatusBar.get_Activity() at CommunityToolkit.Maui.Core.Platform.StatusBar.PlatformSetColor(Color color) at CommunityToolkit.Maui.Core.Platform.StatusBar.SetColor(Color color) at CommunityToolkit.Maui.Behaviors.StatusBarBehavior.OnPropertyChanged(String propertyName) at Microsoft.Maui.Controls.BindableObject.SetValueActual(BindableProperty property, BindablePropertyContext context, Object value, Boolean currentlyApplying, SetValueFlags attributes, Boolean silent) at Microsoft.Maui.Controls.BindableObject.SetValueCore(BindableProperty property, Object value, SetValueFlags attributes, SetValuePrivateFlags privateAttributes) at Microsoft.Maui.Controls.BindableObject.SetValue(BindableProperty property, Object value, Boolean fromStyle, Boolean checkAccess) at Microsoft.Maui.Controls.BindableObject.SetValue(BindableProperty property, Object value) at BlessingsApp.MainPage.InitializeComponent() at BlessingsApp.MainPage..ctor() at BlessingsApp.App..ctor() at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object , Object[] , Boolean ) at System.Reflection.RuntimeConstructorInfo.DoInvoke(Object , BindingFlags , Binder , Object[] , CultureInfo ) at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags , Binder , Object[] , CultureInfo ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite , RuntimeResolverContext ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, Microsoft.Extensions.DependencyInjection, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].VisitCallSiteMain(ServiceCallSite , RuntimeResolverContext ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite , RuntimeResolverContext ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, Microsoft.Extensions.DependencyInjection, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].VisitCallSite(ServiceCallSite , RuntimeResolverContext ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type ) at System.Collections.Concurrent.ConcurrentDictionary`2[[System.Type, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Func`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope, Microsoft.Extensions.DependencyInjection, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].GetOrAdd(Type , Func`2 ) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type , ServiceProviderEngineScope ) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type ) at Microsoft.Maui.MauiContext.WrappedServiceProvider.GetService(Type serviceType) at Microsoft.Maui.MauiContext.WrappedServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider , Type ) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[IApplication](IServiceProvider ) at Microsoft.Maui.MauiApplication.OnCreate() at Android.App.Application.n_OnCreate(IntPtr , IntPtr ) at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(_JniMarshal_PP_V , IntPtr , IntPtr ) at crc6488302ad6e9e4df1a.MauiApplication.n_onCreate(Native Method) at crc6488302ad6e9e4df1a.MauiApplication.onCreate(MauiApplication.java:28) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1266) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6779) at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2132) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.app.ActivityThread.main(ActivityThread.java:7892) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
MauiProgram.cs代码
public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseSkiaSharp() .UseMauiApp<App>().UseMauiCommunityToolkit() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); }); builder.Services .AddScoped<IAuthenticationService, AuthenticationService>() .AddScoped<IUserService, UserService>() .AddScoped<IHttpService, HttpService>() .AddScoped<ILocalStorageService, LocalStorageService>(); builder.Services.AddScoped(x => { var apiUrl = new Uri("http://localhost:5151/users/authenticate"); return new HttpClient() { BaseAddress = apiUrl }; }); builder.Services.AddMauiBlazorWebView(); #if DEBUG builder.Services.AddBlazorWebViewDeveloperTools(); #endif builder.Services.AddSingleton<WeatherForecastService>(); return builder.Build(); } }
解决方案
1. 延迟设置状态栏颜色
问题核心是MainPage初始化阶段(InitializeComponent)调用StatusBarBehavior时,Android Activity还未完全初始化完成,Release模式下的编译优化加剧了这个问题。将状态栏颜色设置延迟到页面显示后执行:
修改MainPage的代码,重写OnAppearing方法:
protected override void OnAppearing() { base.OnAppearing(); // 替换为你需要的颜色 CommunityToolkit.Maui.Core.Platform.StatusBar.SetColor(Colors.DarkBlue); }
同时移除XAML中直接绑定StatusBarBehavior的StatusBarColor属性,避免在初始化阶段触发。
2. 升级Maui Community Toolkit版本
检查当前使用的CommunityToolkit版本,升级到最新稳定版,该问题可能已被官方修复。
3. 调整Release编译选项(临时方案)
如果上述方法无效,可尝试禁用Release模式下的AOT编译:
在项目文件(.csproj)中添加以下配置:
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <AndroidAotEnabled>false</AndroidAotEnabled> </PropertyGroup>
注意:禁用AOT会增加APK体积并降低启动性能,仅作为临时排查方案。
4. 避免在App构造函数中初始化依赖页面
确保App构造函数中没有直接初始化MainPage的复杂逻辑,而是延迟到OnStart或OnResume方法中完成。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

