Como obter notificações quando dispositivos são adicionados, removidos ou modificados (HTML)

[ Este artigo destina-se aos desenvolvedores do Windows 8.x e do Windows Phone 8.x que escrevem aplicativos do Windows Runtime. Se você estiver desenvolvendo para o Windows 10, consulte documentação mais recente]

Este tutorial mostra como enumerar dispositivos dinamicamente. Assim, seu aplicativo pode receber notificações quando dispositivos são adicionados ou removidos, ou quando as propriedades do dispositivo são modificadas.

Use a classe DeviceWatcher para iniciar a enumeração de um dispositivo. Para cada dispositivo encontrado, DeviceWatcher emite um evento Adicionar até a localização de todos os dispositivos e a conclusão da enumeração. Após a conclusão da enumeração inicial, DeviceWatcher continua a emitir eventos quando um dispositivo é adicionado, atualizado ou removido.

O que você precisa saber

Tecnologias

  • Windows Runtime

Pré-requisitos

JavaScript e HTML.

Instruções

Etapa 1: Abrir o Microsoft Visual Studio

Abra uma instância do Visual Studio.

Etapa 2: Criar um novo projeto

Na caixa de diálogo Novo Projeto, nos tipos de projeto JavaScript > Aplicativos da Windows Store, selecione um aplicativo em branco.

Etapa 3: Inserir JavaScript e HTML do aplicativo

Abra Default.html e copie o código HTML a seguir nele, substituindo o conteúdo original.

<!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>

Etapa 4:

Cole este código em default.js, substituindo o conteúdo do arquivo.

    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);
        }
    }

Comentários

O exemplo enumera dispositivos de forma incremental. Ele os adiciona a uma lista toda vez que um dispositivo é encontrado, além de observar se há atualizações. Após a conclusão da enumeração, o aplicativo imprimirá uma lista dos dispositivos. O aplicativo também imprime uma mensagem quando o usuário adiciona, atualiza ou remove dispositivos após a conclusão da enumeração inicial.

Observação  Um aplicativo deve se inscrever em todos os eventos added, removed e updated para ser notificado quando há adições, remoções ou atualizações de dispositivo. Se um aplicativo manipular somente o evento added, ele não receberá uma atualização, quando um dispositivo for adicionado ao sistema após a conclusão da enumeração inicial do dispositivo.