OnSensorChanged method is not getting called

Hrishikesh Garud 21 Reputation points
2021-06-29T18:57:55.553+00:00

I am using stepcounter sensor to detect stepcounts but OnSensorChanged method never gets called.

I have created interface in in PCL-

namespace Pedometer
{
    public interface IStepCounter
    {
        int Steps { get; set; }

        bool IsAvailable();

        void InitSensorService();

        void StopSensorService();
    }
}

Android project code-

[assembly: Dependency(typeof(StepCounter))]
namespace Pedometer.Droid
{
    public class StepCounter : Java.Lang.Object, IStepCounter, ISensorEventListener
    {
        private int StepsCounter = 0;
        private SensorManager sManager;

        public int Steps
        {
            get { return StepsCounter; }
            set { StepsCounter = value; }
        }

        public new void Dispose()
        {
            sManager.UnregisterListener(this);
            sManager.Dispose();
        }

        public void InitSensorService()
        {
            sManager = Android.App.Application.Context.GetSystemService(Context.SensorService) as SensorManager;
            sManager.RegisterListener(this, sManager.GetDefaultSensor(SensorType.StepDetector), SensorDelay.Fastest);

        }

        public void OnAccuracyChanged(Sensor sensor, [GeneratedEnum] SensorStatus accuracy)
        {
            Console.WriteLine("OnAccuracyChanged called");
        }

        public void OnSensorChanged(SensorEvent e)      //This never gets called
        {
            Console.WriteLine(e.ToString());
        }

        public void StopSensorService()
        {
            sManager.UnregisterListener(this);
        }

        public bool IsAvailable()
        {
            return Android.App.Application.Context.PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureSensorStepCounter) && Android.App.Application.Context.PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureSensorStepDetector);
        }
    }
}

My mainpage code-

namespace Pedometer
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            if (DependencyService.Get<IStepCounter>().IsAvailable())
            {
                DependencyService.Get<IStepCounter>().InitSensorService();

                GetCoBut.IsVisible = true;
            }

        }

        private void Button_Clicked(object sender, EventArgs e)
        {
           _actualSteps.Text = DependencyService.Get<IStepCounter>().Steps.ToString();
        }
    }
}
Developer technologies .NET Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-06-30T07:38:57.47+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    You need to add following uses-feature in your AndroidManifest.xml.

       <uses-feature  
              android:name="android.hardware.sensor.stepcounter"  
              android:required="true"/>  
         <uses-feature  
             android:name="android.hardware.sensor.stepdetector"  
             android:required="true"/>  
    

    If you use Android 10 or later, you need to add following permission.

       <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />  
    

    And request runtime permission in android.

       if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ActivityRecognition) != (int)Permission.Granted)  
       {  
                       RequestPermissions(new string[] { Manifest.Permission.ActivityRecognition }, 0);  
       }  
    

    Then I find you sManager.RegisterListener lack of sensor. Here is my editted StepCounter.cs. I test it in my Google pixel, it OnSensorChanged will execute, and could get the steps.

       using Android.App;  
       using Android.Content;  
       using Android.Hardware;  
       using Android.OS;  
       using Android.Runtime;  
       using Android.Views;  
       using Android.Widget;  
       using CustomEntryDemo.Droid;  
       using System;  
       using System.Collections.Generic;  
       using System.Linq;  
       using System.Text;  
       using Xamarin.Forms;  
         
       [ assembly: Dependency(typeof(StepCounter))]  
       namespace CustomEntryDemo.Droid  
       {  
           public class StepCounter : Java.Lang.Object, IStepCounter, ISensorEventListener  
           {  
               private int StepsCounter = 0;  
               private SensorManager sManager;  
         
               public int Steps  
               {  
                   get { return StepsCounter; }  
                   set { StepsCounter = value; }  
               }  
         
               public new void Dispose()  
               {  
                   sManager.UnregisterListener(this);  
                   sManager.Dispose();  
               }  
               //private static final int sensorTypeD = Sensor.TYPE_STEP_DETECTOR;  
               //  private static final int sensorTypeC = Sensor.TYPE_STEP_COUNTER;  
               private Sensor mStepCount;  
               private Sensor mStepDetector;  
         
               public void InitSensorService()  
               {  
                   sManager = Android.App.Application.Context.GetSystemService(Context.SensorService) as SensorManager;  
                    
                   mStepCount = sManager.GetDefaultSensor(SensorType.StepDetector);  
                   mStepDetector = sManager.GetDefaultSensor(SensorType.StepCounter);  
         
         
                   sManager.RegisterListener(this, mStepCount, SensorDelay.Fastest);  
                   sManager.RegisterListener(this, mStepDetector, SensorDelay.Fastest);  
         
               }  
         
               public void OnAccuracyChanged(Sensor sensor, [GeneratedEnum] SensorStatus accuracy)  
               {  
                   Console.WriteLine("OnAccuracyChanged called");  
               }  
         
               public void OnSensorChanged(SensorEvent e)       
               {  
                   Console.WriteLine(e.ToString());  
         
                   if (e.Sensor.Type== SensorType.StepCounter) {   
       			//setStepCount(event.values [0]);  
                   }  
       		    if (e.Sensor.Type == SensorType.StepDetector) {   
       			    if (e.Values[0]==1.0) {  
                                Steps++;  
                       }  
                   }  
         
         
               }  
         
               public void StopSensorService()  
               {  
                   sManager.UnregisterListener(this);  
               }  
         
               public bool IsAvailable()  
               {  
                   return Android.App.Application.Context.PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureSensorStepCounter) && Android.App.Application.Context.PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureSensorStepDetector);  
               }  
           }  
       }  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.