Using device sensors

Tizen provides APIs to monitor the movement, location, etc. of Galaxy Watch and measure the user's heart rate in real time. Galaxy Watch doesn't support all sensors, but it does support sensors that are useful to the users. Since the availability of the sensor depends on the support of the relevant hardware/software, you need to check the availability of the sensor on a device if you want to access the sensors in your app.

Checking sensor's availability

Not all Galaxy Watch support all sensors, so you need to make sure that the sensors are supported in the current device before using it in your application.

First add the reference to Tizen.Sensors:

using Tizen.Sensor;

There are two ways to check sensor availability:

  • use the feature key

    bool pedometerSupported;
    const string pedometerFeature = "http://tizen.org/feature/sensor.pedometer";
    if (!Tizen.System.Information.TryGetValue<bool>(pedometerFeature, out pedometerSupported))
    {
        // Check if the name of the specified feature key is right
    }
    if (pedometerSupported)
    {
        // You can use the pedometer sensor data
    }
    
  • use sensor's IsSupported property

    if (Pedometer.IsSupported)
    {
        // You can use the pedometer sensor data
    }
    

Declaring device privilege and requesting user permission

Tizen protects user information such as contacts, calendar, and user's app usage history and certain device resources such as camera, microphone, location, sensor, and media storage from being used without your consent. In order for an app to access sensitive information or resources related to the user, you must declare device privileges in the app manifest file and then request user's permission at runtime for privacy privileges, which are related to sensitive user data.

Declare device privilege

MySteps app requires user's step count provided by the Pedometer class. To use the APIs related to the user's health information such as HeartRateMonitor, Pedometer, and SleepMonitor, healthinfo privilege must be declared in the tizen-manifest.xml file of the app. Take the following steps to declare healthinfo privilege:

  1. Select the tizen-manifest.xml in the Solution Explorer of Visual Studio.

    Figure 1. In Visual Studio Solution Explorer view, locate tizen-manifest.xml
  2. Click Privileges in the left sidebar and Click Add button.

    Figure 2. Adding device privilege
  3. In the list of Platform defined privileges, find http://tizen.org/privilege/healthinfo or type healthinfo in the search bar, select the privilege and press OK button.

    Figure 3. Adding healthinfo privilege

Ask user's permission

To access privacy privileges, the application must explicitly ask for user's permission at runtime. You can check permission to access the user's private data for more information. Use the PrivacyPrivilegeManager to request access to the user's health data.

First add the reference to Tizen.Security:

using Tizen.Security;

You can ask the user's permission as shown in the following example:

...
public partial class App : Application
{
....
    protected override void OnStart()
    {
        // The app has to request the permission to access health data
        RequestPermissionHealthInfoAsync();
    }
    private async void RequestPermissionHealthInfoAsync()
    {
        var result = await RequestAsync("http://tizen.org/privilege/healthinfo");
        if (!result)
        {
            await MainPage.DisplayAlert("Alert", "This app cannot access your health information. So it will be terminated.", "OK");
            Application.Current.Quit();
        }
    }

    /// <summary>
    /// Asks the user to grant the permission at runtime
    /// </summary>
    /// <param name="privilege">The privilege name to check for</param>
    /// <returns>bool value that indicates whether the permission has been granted or not</returns>
    private async Task<bool> RequestAsync(string privilege)
    {
        // first make sure the user has given permission to use the privacy-related permissions in the app.
        switch (PrivacyPrivilegeManager.CheckPermission(privilege))
        {
            case CheckResult.Allow:
                // already allowed
                return true;
            case CheckResult.Deny:
            case CheckResult.Ask:
                var tcs = new TaskCompletionSource<bool>();
                var response = PrivacyPrivilegeManager.GetResponseContext(privilege);
                PrivacyPrivilegeManager.ResponseContext context = null;
                
                if (response.TryGetTarget(out context))
                {
                    context.ResponseFetched += (s, e) =>
                    {
                        bool result = false;
                        if (e.result == RequestResult.AllowForever)
                        {
                            result = true;
                        }
                        
                        tcs.SetResult(result);
                    };
                }
      // Ask the user to give the app permission to use the user's personal information
                PrivacyPrivilegeManager.RequestPermission(privilege);
                
                return await tcs.Task;
            default:
                return false;
        }
    }
}

You should ask the user to give your app permission to use the user's personal information by calling PrivacyPrivilegeManager.RequestPermission(privilege). If you rerun the application, a new pop-up screen will appear. Click the check mark on the right.

Figure 4. Asking permission to user's private data

Tracking the user's steps using pedometer

When the user clicks the Start button in the MainPage, we want to monitor the user's steps with a pedometer sensor in Galaxy Watch. To activate the pedometer sensor, write StepCountPage.xaml.cs as below. The code demonstrates how to get a controller instance of the device's pedometer and activate the sensor:

public partial class StepCountPage : ContentPage
{
    Pedometer pedometer;
    public StepCountPage()
    {
        ...
        InitializeComponent();
        pedometer = new Pedometer();
        pedometer.Start();
    }
}

We want to display the step count data on the Label whenever the step count changes. To do this, we need to access the Label in our code behind. Use the x:Name attribute in XAML to add a unique reference which can be accessed in code behind. Add a x:Name attribute to Label and assign a string "stepCountLabel":

<Label Text="0 Steps"
       x:Name="stepCountLabel"
       FontSize="Large"
       VerticalOptions="CenterAndExpand"
       HorizontalOptions="CenterAndExpand"/>

The code-behind file can access the Label object defined in XAML using the stepCountLabel name assigned with the x:Name attribute. Now you can update the text of Label to show the updated step count.

MySteps can subscribe to the events of pedometer's data updates by attaching an event handler(UpdateData()) to the pedometer.DataUpdated event. The following code shows you how to do this:

public StepCountPage()
{
  ...
  pedometer = new Pedometer();
  pedometer.DataUpdated += UpdateData;
  pedometer.Start();
}

void UpdateData(object s, EventArgs e)
{
  stepCountLabel.Text = pedometer.StepCount.ToString() + " Steps";
}

Testing on Tizen wearable emulator

In order to test the pedometer function on an emulator, you need to trigger the virtual sensor of the emulator:

  1. Right-click anywhere on an emulator and click Control Panel.

    Figure 5. Click Control Panel.
  2. Click the Next button at the bottom right of the Tizen Emulator Control Panel window.

    Figure 6. control panel
  3. Press the Pedometer and select Walk to update the step count for your application.

    Figure 7. Manipulate virtual pedometer.

In the last tutorial of the Get Started series, we will introduce the specialized UIs for Samsung Galaxy Watch.