Share via


如何儲存上次使用的裝置以再次使用 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

這個主題說明如何呼叫 DeviceInformation.CreateFromIdAsync,從儲存的裝置識別碼取得裝置資訊。

您必須知道的事

技術

  • Windows Runtime

先決條件

您應該熟悉 JavaScript 和 HTML。

指示

將裝置介面識別碼傳送到 createFromIdAsync

第一次執行需要使用裝置的應用程式時,它會列舉可用的裝置,從列舉結果選取 DeviceInformation 物件,然後將 DeviceInformation.Id 屬性傳送到 Windows 執行階段 API 以存取裝置。 讓應用程式儲存這個裝置識別碼是很實用的做法,如此一來,下次應用程式執行時會在執行另一次列舉前先檢查是否有上次使用過的裝置,然後就可以更快速地啟動。

這個函式的 savedDeviceID 參數是上次使用裝置的識別碼。下列程式碼會呼叫 createFromIdAsync 來建立 DeviceInformation 物件,並定義兩個匿名函式來處理成功和錯誤的結果。如果方法成功,應用程式會使用 DeviceInformation 物件先判斷是否已啟用裝置介面,然後再將它傳送到 API 以使用裝置。

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