C# 从依赖项服务访问UI

C# 从依赖项服务访问UI,c#,android,xamarin,xamarin.forms,C#,Android,Xamarin,Xamarin.forms,我想在Xamarin.Forms项目中使用StepCounter。 如果我理解正确,我需要使用依赖服务,为stepcounter编写接口,并在Android/IOS应用程序上实现 问题是,当步进传感器状态改变时,我想随时更新ui控件(文本)。例如,在安卓系统中,我们有 using Android.Hardware; /*Dependency Service header [assembly: Dependency(typeof(..... */ ... namespace tmp { pub

我想在Xamarin.Forms项目中使用StepCounter。
如果我理解正确,我需要使用依赖服务,为stepcounter编写接口,并在Android/IOS应用程序上实现

问题是,当步进传感器状态改变时,我想随时更新ui控件(文本)。例如,在安卓系统中,我们有

using Android.Hardware;
/*Dependency Service header 
[assembly: Dependency(typeof(.....
*/
...
namespace tmp
{
 public class Stepper : ISensorEventListener, INameOfDependencyInterface
 {
   public static void Init()
    {
    SensorManager senMgr = (SensorManager)GetSystemService(SensorService);
         Sensor counter = senMgr.GetDefaultSensor(SensorType.StepCounter);

         if (counter != null)
         {
             senMgr.RegisterListener(this, counter, SensorDelay.Normal);
         }
    }
  public void OnSensorChanged(SensorEvent e)
    {
        /*something that change text on ui*/
    }
 }
}
在这里,正如您所看到的,我想在OnSensorChanged void中更改UI中的文本

也许这个问题有更好的解决方案,比如:

  • 从平台依赖性服务类实现调用PCL或在PCL中生成类似侦听器的东西

  • 在PCL make timer中,它对依赖项服务进行响应并获取步进计数器值,例如,每秒一次

  • 忘记Xamarin.Forms并迁移到Xamarin.Native


  • 我向您的
    Init
    构造函数添加了一个
    Action
    ,当传感器发生变化时,它将被调用:

    public class Stepper : ISensorEventListener, INameOfDependencyInterface
    {
    
        private Action<float> _stepCountChanged;
    
        public static void Init(Action<float> stepCountChanged)
        {
            SensorManager senMgr = (SensorManager)GetSystemService(SensorService);
            Sensor counter = senMgr.GetDefaultSensor(SensorType.StepCounter);
    
            if (counter != null)
            {
                senMgr.RegisterListener(this, counter, SensorDelay.Normal);
            }
    
            _stepCountChanged = stepCountChanged;
        }
        public void OnSensorChanged(SensorEvent e)
        {
            _stepCountChanged(e.Values.First());
    
        }
    }
    
    DependencyService.Get<...>().Init((steps) => { 
        // Label.Steps = steps;
    });