Essential practices

Once you know the basics of configuring the development environment and building apps utilising the Lumia SensorCore SDK, there are still a few more things developer needs to know. There are some general patterns and practices on how one should use SensorCore to ensure stability and compatibility. Please note that the same essential patterns and practices are used in the samples in identical way, although they are only documented in detail in here. In this section we will go through initialising, error handling, and application lifecycle management.

Initialising SensorCore

To make it easier to switch between the actual hardware class and the simulator, we use alias for the class, and refer to it with Monitor keyword throughout the sample. Here is a sample from Places :

using Monitor = Lumia.Sense.PlaceMonitor;

Verifying hardware support

It is important to understand that SensorCore SDK relies on hardware which is not present on all phones. For that reason the first thing you should do is to check if the device supports the part of the SensorCore SDK you are using.

You can check if a sensor is supported by the device by using IsSupportedAsync() method.

if( !await StepCounter.IsSupportedAsync() )
{
     // Show error message or hide UI controls...
}

To check for specific feature availability you can use SenseHelper.GetSupportedCapabilitiesAsync().

if( ( await SenseHelper.GetSupportedCapabilitiesAsync() ).MotionDataSettingsTriggers )
{
         await RegisterBackgroundTask( SenseTrigger.MotionDataCleared, "motiondatatrigger", "BackgroundTasks.MotionDataTriggerTask" );
}

Using this API call you can query the following capabilities:

  • StepCounterTrigger: Tells whether step counter background task trigger is supported or not. This trigger is raised when step counter detects movement.
  • MotionDataSettingsTriggers: Tells whether background task triggers for monitoring settings changes affecting Motion data are supported or not. These settings include Motion data system setting and location system setting.

See SensorCore SDK triggers for background tasks section for more information on background triggers.

Calling the Lumia SensorCore SDK safely

Whenever you call the API, it is important to check that the required services (Location and Motion) are enabled and that the call does not throw an exception. We have provided a wrapper to use when calling the SensorCore SDK which will take care of these things for you.

private async Task<bool> CallSensorcoreApiAsync(Func<Task> action)
{
    Exception failure = null;
    try
    {
        await action();
    }
    catch (Exception e)
    {
        failure = e;
    }

    if (failure != null)
    {
        MessageDialog dialog;
        switch (SenseHelper.GetSenseError(failure.HResult))
        {
            case SenseError.LocationDisabled:
                dialog = new MessageDialog("Location has been disabled. Do you want to open Location settings now?", "Information");
                dialog.Commands.Add(new UICommand("Yes", async cmd => await SenseHelper.LaunchLocationSettingsAsync()));
                dialog.Commands.Add(new UICommand("No"));
                await dialog.ShowAsync();
                new System.Threading.ManualResetEvent(false).WaitOne(500);
                return false;

            case SenseError.SenseDisabled:
                dialog = new MessageDialog("Motion data has been disabled. Do you want to open Motion data settings now?", "Information");
                dialog.Commands.Add(new UICommand("Yes", async cmd => await SenseHelper.LaunchSenseSettingsAsync()));
                dialog.Commands.Add(new UICommand("No"));
                await dialog.ShowAsync();
                new System.Threading.ManualResetEvent(false).WaitOne(500);
                return false;

            default:
                dialog = new MessageDialog("Failure: " + SenseHelper.GetSenseError(failure.HResult), "");
                await dialog.ShowAsync();
                return false;
        }
    }

    return true;
}

Before we can use any part of the SensorCore SDK APIs, we need to initialize it first with call to GetDefaultAsync. You can call the initialization using the wrapper provided above like this:

if (await CallSensorcoreApiAsync(async () => { monitor = await Monitor.GetDefaultAsync(); }))

If the call to the SensorCore APIs failed, we exit the application at this point.

Activation and deactivation

With the Universal apps the navigation model differs from Silverlight, and you have to handle the activation and deactivation of the sensors differently. We are adding a handler for the VisibilityChanged event, where we activate and deactivate the Place Monitor when the application is put to background or when it gets focus again. This can be done with a traditional event handler as well; below is a short way of doing the same thing.

Window.Current.VisibilityChanged += async (oo, ee) =>
{
    if (!ee.Visible)
    {
        await CallSensorcoreApiAsync(async () => {
            if (_sensor != null)
            {
                await _sensor.DeactivateAsync();
            }
        });
    }
    else
    {
        await CallSensorcoreApiAsync(async () => {
            if (_sensor != null) {
                await _sensor.ActivateAsync(); 
            } 
        });
    }
}
With Silverlight we would do the same like this:
protected async override void OnNavigatedTo(NavigationEventArgs e) 
{
    if (_stepCounter == null)
    {
        await Initialize();
    }
    await _stepCounter.ActivateAsync(); 
}

protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e) {
    await _stepCounter.DeactivateAsync(); 
}  

Error handling

Lumia SensorCore SDK APIs return errors by throwing exceptions. You can get more detailed information about the exception by using SenseHelper.GetSenseError().

Apps utilising SensorCore SDK can also be installed on devices that do not support SensorCore SDK functionalities. App should prepare for a case where no sensor or sensor data is available. If an app has no function without SensorCore SDK, it should be stated clearly in the Store description.

One of the most important error situations is when a method fails due to user having disabled either location services or motion data collection. You should provide the user with an easy way of going to system settings to enable the necessary feature or features. You can, for example, encapsulate the API calls with the CallSenseApiAsync we defined earlier in the Quick Start section to handle any errors.

You can then use that method for wrapping all SensorCore SDK related calls:

if (await CallSensorcoreApiAsync(async() => { 
    _stepCounter = await StepCounter.GetDefaultAsync();
}))
{
    // Success
}
else
{
    // Failure
}


Last updated 6 October 2014

Back to top

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×