System.PlatformNotSupportedException: 此平台不支持该操作。(Android)
System.PlatformNotSupportedException: Operation is not supported on this platform. (Android)
ID: dotnet/maui-platform-not-supported-android
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .NET MAUI 6.0 | active | — | — | — |
| .NET MAUI 7.0 | active | — | — | — |
| .NET MAUI 8.0 | active | — | — | — |
| Xamarin.Android 12.0 | active | — | — | — |
| Xamarin.Android 13.0 | active | — | — | — |
根因分析
.NET MAUI 或 Xamarin.Forms 应用程序调用了 Android 平台不可用的 API,例如 Windows 特定的文件系统 API 或 iOS 专属框架,而没有进行适当的平台检查。
English
A .NET MAUI or Xamarin.Forms app is calling an API that is not available on the Android platform, such as Windows-specific filesystem APIs or iOS-only frameworks, without proper platform checks.
官方文档
https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/解决方案
-
Use conditional compilation with platform-specific implementations. Example: #if ANDROID // Android-specific code using Android.Content.Intent #elif IOS // iOS-specific code using UIKit.UIApplication #endif
-
Use the DeviceInfo.Platform property from Xamarin.Essentials or MAUI Essentials to check at runtime: if (DeviceInfo.Platform == DevicePlatform.Android) { /* Android code */ } else { /* fallback */ } -
Use dependency injection with platform-specific services. Register an interface in the shared project and implement it in each platform project. Example: services.AddSingleton<IFileService, AndroidFileService>();
无效尝试
常见但无效的做法:
-
Adding a try-catch around the call and ignoring the exception.
90% 失败
This suppresses the error but does not provide the intended functionality; it may lead to silent data loss or incorrect behavior.
-
Using conditional compilation (#if ANDROID) without implementing an alternative for Android.
80% 失败
If the alternative is not implemented, the code will not execute at all, leaving functionality missing.
-
Downgrading the target framework to an older version that supports the API.
100% 失败
The API is platform-specific; downgrading does not change the underlying OS capabilities.