DependencyService.Get <InterfaceImplemetation>() возвращает null - PullRequest
0 голосов
/ 27 мая 2020

Я реализовал DependencyService для изменения ориентации устройства для определенной c страницы.

ScreenRotation.cs

[assembly: Dependency(typeof(WhaleEstimate.Droid.ScreenRotation))]
        namespace WhaleEstimate.Droid
        {
            class ScreenRotation : IScreenRotation
            {
                public void DisableScreenRotation()
                {
                    Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
                }

                public void EnableScreenRotation()
                {
                    Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.FullSensor;
                }
            }
        }

Код в PCL:

private IScreenRotation screenRotationService;
screenRotationService = DependencyService.Get<IScreenRotation>();
if (screenRotationService != null)
{
     screenRotationService.EnableScreenRotation();
}

При выполнении достигает фрагмента кода в условии if. Затем выбрасывается исключение NullReferenceException. Я совершенно не знаю, почему он достигает фрагмента кода внутри предложения if и почему объект имеет значение null.

EDIT

Информация об исключении: enter image description here

Ответы [ 3 ]

1 голос
/ 27 мая 2020

Вы получаете NullReferenceException, вероятно, потому что Android.Content имеет значение null, что дает вам исключение, попробуйте изменить ScreenRotation на это, чтобы получить контекст действия:

public class ScreenRotation : IScreenRotation
{
    public void DisableScreenRotation()
    {
        var activity = (Activity)Forms.Context;
        activity.RequestedOrientation = ScreenOrientation.Portrait; 
    }

    public void EnableScreenRotation()
    {
         var activity = (Activity)Forms.Context;
         activity.RequestedOrientation = ScreenOrientation.FullSensor; 
    }
}
0 голосов
/ 27 мая 2020

Привет, я использовал плагин CurrentActivity, и он у меня работает. Я думаю, вы забыли инициализировать плагин в своем Android файле проекта MainActivity.cs

MainActivity.cs

protected override void OnCreate(Bundle savedInstanceState)
        {

            base.OnCreate(savedInstanceState);
            Xamarin.Forms.Forms.SetFlags("Expander_Experimental");
            CrossCurrentActivity.Current.Init(this, savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }

Android

ScreenRotation.cs

using Plugin.CurrentActivity;
using Xamarin.Forms;
[assembly: Dependency(typeof(TestMobileApp.Droid.ScreenRotation))]
namespace TestMobileApp.Droid
{
    public class ScreenRotation : IScreenRotation
    {
        public void DisableScreenRotation()
        {
            CrossCurrentActivity.Current.Activity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
        }

        public void EnableScreenRotation()
        {
            CrossCurrentActivity.Current.Activity.RequestedOrientation = Android.Content.PM.ScreenOrientation.FullSensor;

        }
    }
}
0 голосов
/ 27 мая 2020

Первый. Вы зарегистрировали службу зависимостей в Initialization ?. В app.xaml.cs

DependencyService.Register<IService, Service>();

Также попробуйте сделать класс publi c

...