How to save the last used device to reuse later (HTML)
This topic explains how to get device information from a saved device ID, by calling DeviceInformation.CreateFromIdAsync.
What you need to know
Technologies
- Windows Runtime
Prerequisites
You should be familiar with JavaScript and HTML.
Instructions
Pass the device interface ID to createFromIdAsync
The first time you run an app that needs to use devices, it enumerates available devices, selects a DeviceInformation object from the enumeration results, and passes the DeviceInformation.Id property to a Windows Runtime API for accessing the device. It can be good practice for an app to save this device ID, so that the next time the app runs, it can start up more quickly by checking whether the last-used device is available, before starting another enumeration.
This function's savedDeviceID parameter is an ID of the last-used device. The following code calls createFromIdAsync to create a DeviceInformation object, and defines two anonymous functions to handle success and error results. If the method succeeds, the app uses the DeviceInformation object to determine whether the device interface is enabled before passing it on to an API for using the device.
function getLastUsedDeviceInfo(savedDeviceID) {
// Create a DeviceInformation object from the ID.
var Enum = Windows.Devices.Enumeration;
var DevInf = Enum.DeviceInformation;
DevInf.createFromIdAsync(savedDeviceId).then(
function(devinfo) {
printMessage("Found last-used device. Name: " + devinfo.name);
if (devinfo.isEnabled) {
// Add code to pass devinfo.id to an appropriate API.
// For instance, if devinfo is a camera, use the id property
// to select the camera as the one the Camera Capture API
// should use, by setting the VideoDeviceId property of
// Windows.Media.Capture.MediaCaptureInitializationSettings.
} else {
// Handle the case of the device not being enabled.
}
},
function (e) {
displayError("Failed to create DeviceInformation: " + e.message);
// Since the last-used device wasn't found, add code here
// to call FindAllAsync or CreateWatcher to find other devices.
});
}