2

I am creating a universal windows application which will be used on both desktop, and mobile devices. The mobile devices will use vibration API.

//Vibrate the device
VibrationDevice.GetDefault().Vibrate(TimeSpan.FromMilliseconds(100));

I have added the necessary extension to the project to allow for this:

Project reference extensions

The Windows Mobile Extensions for the UWP will of course, not be present on desktop machines, therefore I need to conditionally test to check whether the SDK is available so I can execute the Vibrate method.

Essentially, if the app is running on the desktop, I do not want to execute the Vibrate method, otherwise I'll receive the exception:

An exception of type 'System.TypeLoadException' occurred in Encore.Scanner.UI.exe but was not handled in user code

Additional information: Requested Windows Runtime type 'Windows.Phone.Devices.Notification.VibrationDevice' is not registered.

Is there a way I can check whether the SDK is available? Something like this:

if (...windows mobile extension is present)
{
    //Vibrate the device.    
    VibrationDevice.GetDefault().Vibrate(TimeSpan.FromMilliseconds(100));
}
Community
  • 1
  • 1
Mike Eason
  • 9,525
  • 2
  • 38
  • 63

1 Answers1

4

I found what I needed. Here's how I achieved this if anyone stumbles across this problem in future.

if (ApiInformation.IsTypePresent("Windows.Phone.Devices.Notification.VibrationDevice"))
{
    ...
Mike Eason
  • 9,525
  • 2
  • 38
  • 63
  • This is helpful! However As part of the universal app framework if this vibration code was run on a non suitable device then would it crash? Surely it would just ignore the action? – Harvey Nov 04 '15 at 12:56
  • @Harvey It would probably be worth doing a null check on `VibrationDevice.GetDefault()`. Just in case. – Mike Eason Nov 04 '15 at 12:58
  • Okay, I'll bare this in mind as I would probably never have taken this approach. Thanks again! – Harvey Nov 04 '15 at 12:59
  • This is the documented recommended way to do things: https://msdn.microsoft.com/en-us/library/windows/apps/dn894631.aspx#writing_code . It will ensure the VibrationDevice type is present and can be called, but like Mike says you'll still want to make check that the calls succeed. – Rob Caplan - MSFT Nov 05 '15 at 23:07
  • @MikeEason - Are you sure the null check on `VibrationDevice.GetDefault()` is necessary? If you call `GetDefault()` on desktop, it crashes with `System.TypeLoadException`. So I think it might be safe to assume that if it doesn't crash, then vibration is available. – ndbroadbent May 16 '17 at 09:49
  • @RobCaplan-MSFT - I couldn't find anything related to vibration in the article you linked, it might have changed in the last few years. – ndbroadbent May 16 '17 at 09:50
  • 1
    Also I just tested on the Windows Phone Emulator. It reports that Vibration is available, but calling vibrate doesn't do anything. So I don't think the null check is necessary. – ndbroadbent May 16 '17 at 09:57