我正在嘗試從 Xamarin 遷移到 MAUI。
以下代碼完美喚醒。
Xamarin 專案:
DependencyService.Get<IMyService>().Test();
安卓:
[assembly: Dependency(typeof(MyService))]
namespace MyProject.Android
{
public class MyService: IMyService
{
public void Test(){
////
}
}
}
對于 IOS 和 Windows 等等。
但是 MAUI 的DependencyService.Get 總是回傳null。我找不到必須進行哪些新更改。在我的主專案中重新撰寫基于 DependencyService 的所有代碼會很痛苦。
在這種情況下應該做出哪些改變?
uj5u.com熱心網友回復:
您在 MAUI 中沒有平臺依賴服務的概念,您可以使用條件編譯或部分類來完成您需要做的事情。
因此,如果您在此處查看 Microsoft 博客:https ://learn.microsoft.com/en-us/dotnet/maui/platform-integration/invoke-platform-code ,它將向您展示如何使用這兩種方式來呼叫平臺代碼.
所以通過條件編譯得到Orientation:
#if ANDROID
using Android.Content;
using Android.Views;
using Android.Runtime;
#elif IOS
using UIKit;
#endif
using InvokePlatformCodeDemos.Services;
namespace InvokePlatformCodeDemos.Services.ConditionalCompilation
{
public class DeviceOrientationService
{
public DeviceOrientation GetOrientation()
{
#if ANDROID
IWindowManager windowManager = Android.App.Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
SurfaceOrientation orientation = windowManager.DefaultDisplay.Rotation;
bool isLandscape = orientation == SurfaceOrientation.Rotation90 || orientation == SurfaceOrientation.Rotation270;
return isLandscape ? DeviceOrientation.Landscape : DeviceOrientation.Portrait;
#elif IOS
UIInterfaceOrientation orientation = UIApplication.SharedApplication.StatusBarOrientation;
bool isPortrait = orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown;
return isPortrait ? DeviceOrientation.Portrait : DeviceOrientation.Landscape;
#else
return DeviceOrientation.Undefined;
#endif
}
}
}
或部分課程
共享代碼:
namespace InvokePlatformCodeDemos.Services.PartialMethods
{
public partial class DeviceOrientationService
{
public partial DeviceOrientation GetOrientation();
}
}
平臺代碼:
using Android.Content;
using Android.Runtime;
using Android.Views;
namespace InvokePlatformCodeDemos.Services.PartialMethods;
public partial class DeviceOrientationService
{
public partial DeviceOrientation GetOrientation()
{
IWindowManager windowManager = Android.App.Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
SurfaceOrientation orientation = windowManager.DefaultDisplay.Rotation;
bool isLandscape = orientation == SurfaceOrientation.Rotation90 || orientation == SurfaceOrientation.Rotation270;
return isLandscape ? DeviceOrientation.Landscape : DeviceOrientation.Portrait;
}
}
祝你好運!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524209.html
標籤:。网毛伊岛
上一篇:如何減少if陳述句?
