Поделиться через


Как получать уведомления при добавлении, удалении или изменении устройств (HTML)

[ Эта статья адресована разработчикам приложений среды выполнения Windows для Windows 8.x и Windows Phone 8.x. При разработке приложений для Windows 10 см. раздел последняя документация]

В этом учебнике рассказывается о динамическом перечислении устройств. Приложение может получать уведомления в случае удаления или добавления устройства, а также изменения его свойств.

Чтобы начать перечисление устройств, используется класс DeviceWatcher. Пока все устройства не будут обнаружены, а перечисление не будет завершено, DeviceWatcher генерирует событие Add для каждого обнаруженного устройства. После завершения первоначального перечисления DeviceWatcher продолжает создавать события при добавлении, обновлении или удалении устройств.

Что необходимо знать

Технологии

  • Windows Runtime

Необходимые условия

JavaScript и HTML

Инструкции

Этап 1: Открытие Microsoft Visual Studio

Откройте экземпляр программы Visual Studio.

Этап 2: Создание нового проекта

В диалоговом окне Создать проект выберите тип проекта JavaScript > Приложения Магазина Windows и укажите пустое приложение.

Этап 3: Вставка кодов JavaScript и HTML приложения

Откройте ваш файл Default.html и скопируйте в него следующий HTML-код, заменяя исходное содержимое.

<!DOCTYPE html>
<html>
<head>
  <title>Device Enumeration Sample</title>
  <meta charset="utf-8" />
  <script src="/js/default.js"></script>
</head>
<body role="application">
    <h1>Device Enumeration Sample</h1>
    <h2 >Input</h2>
    <div >            
            <div >
            <p>This example incrementally enumerates devices, adding them to a list each time a device is found, and also watching for updates.
               Once enumeration is complete, the list of devices is printed.</p> 
                <input type="button" value="Watch(All Devices)" onclick="WatchDevices()"/>
                <br /><br />

                <input type="button" value="Stop" onclick="stopWatcher()"/>
                <br /><br />
            </div>
    </div>

    <h2 > Output</h2>
            <div id="statusMessage"></div>
            <!--  Output -->
            <div  id="output"></div>
</body>
</html>

Этап 4:

Вставьте этот код в файл default.js с заменой содержимого файла.

    var watcher;
    var isEnumerationComplete = false;
    var deviceArray = new Array(); // Saves the enumeration results

    function WatchDevices() {
        try {
            output.innerHTML = ""; // clear output field

            watcher = 
                Windows.Devices.Enumeration.DeviceInformation.createWatcher();
            // Add event handlers
            watcher.addEventListener("added", onAdded);
            watcher.addEventListener("removed", onRemoved);
            watcher.addEventListener("updated", onUpdated);
            watcher.addEventListener("enumerationcompleted", 
                onEnumerationCompleted);
            watcher.addEventListener("stopped", onStopped);
            // Start enumerating and listening for events
            watcher.start();
        } catch (e) {
            document.getElementById("statusMessage").innerHTML = 
                "Failed to create watcher, error: " + e.message;
        }
    }

    function stopWatcher() {
        try {
            watcher.stop();
        }
        catch (e) {
            document.getElementById("statusMessage").innerHTML = 
                "Failed to stop watcher: " + e.message;
        }
    }

    function onAdded(devinfo) {
        document.getElementById("output").innerHTML += "<p>Device added: " + 
            devinfo.name + "</p>";
        deviceArray.push(devinfo);
        if (isEnumerationComplete) {
            output.innerHTML = ""; // clear output field
            printDeviceArray(document.getElementById("output"));
        }
        
    }

    function onUpdated(devUpdate) {
        document.getElementById("output").innerHTML += "<p>Device updated.</p>";
        for (var i = 0; i < deviceArray.length; i++) {
            if (deviceArray[i].id == devUpdate.id) {
                deviceArray[i].update(devUpdate);
            }
        }
        output.innerHTML = ""; // clear output field
        printDeviceArray(document.getElementById("output"));
    }

    function onRemoved(devupdate) {
        document.getElementById("output").innerHTML += "<p>Device removed.</p>";
        for (var i = 0; i < deviceArray.length; i++) {
            if (deviceArray[i].id == devupdate.id) {
                deviceArray[i].slice(devupdate);
            }
        }
        output.innerHTML = ""; // clear output field
        printDeviceArray(document.getElementById("output"));
    }

    function onEnumerationCompleted(obj) {
        isEnumerationComplete = true;
        document.getElementById("output").innerHTML += 
            "<p>Enumeration Completed.</p>";
        printDeviceArray(document.getElementById("output"));
    }

    function onStopped(obj) {
        document.getElementById("output").innerHTML += "<p>Stopped.</p>";
        if (watcher.status == Windows.Devices.Enumeration.DeviceWatcherStatus.aborted) {
           document.getElementById("output").innerHTML += 
            "<p>Enumeration stopped unexpectedly. </p>";
           document.getElementById("output").innerHTML += 
            "<p>Click the Watch button to restart enumeration.</p>";
        } else if (watcher.status == Windows.Devices.Enumeration.DeviceWatcherStatus.stopped) {
           document.getElementById("output").innerHTML += 
            "<p>You requested to stop enumeration. </p>";
           document.getElementById("output").innerHTML += 
            "<p>Click the Watch button to restart enumeration.</p>";
        }

    }


    // Prints the friendly name of the device interface, 
    // its ID (device interface path), and whether it is enabled.
    function printDevice(deviceInterface, outputDestination) {
        outputDestination.innerHTML += "<p>Name: " + 
            deviceInterface.name + "<p/>"; 
        outputDestination.innerHTML += "<p>Interface ID: " + 
            deviceInterface.id + "<p/>";    
        outputDestination.innerHTML += "<p>Enabled: " + 
            deviceInterface.isEnabled + "<p/>";
        outputDestination.innerHTML += "<br />";
    }

    function printDeviceArray(outputDestination) {
        for (var i = 0; i < deviceArray.length; i++) {
            printDevice(deviceArray[i], outputDestination);
        }
    }

Замечания

В этом примере по очереди перечисляются устройства. Приложение добавляет их в список при каждом обнаружении устройства и следит за обновлениями. По завершении перечисления приложение выводит список устройств. Кроме того, приложение выводит сообщения при добавлении, обновлении и удалении устройств по завершении первоначального перечисления.

Примечание  Чтобы получать уведомления о добавлении, удалении и обновлении устройств, приложение должно быть подписано на все события added, removed и updated. Если приложение обрабатывает только событие added, оно не получит обновление при добавлении устройства в систему после завершения первоначального перечисления устройств.