장치가 추가, 제거 또는 변경된 경우 알림을 표시하는 방법(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 이벤트만 처리할 경우에는 초기 장치 열거가 완료된 후 시스템에 장치가 추가되면 업데이트를 받지 않습니다.