要求使用者權限
本主題描述如何向使用者要求許可權以使用感應器。 如需感應器 API 中許可權的背景資訊,請參閱 管理使用者權限。
下列範例說明一些常見的案例,您可以在其中選擇要求使用者權限。
下列範例程式碼只會使用非同步方法呼叫,依類型要求從感應器管理員擷取的所有感應器許可權。 平臺會開啟對話方塊,提示使用者只啟用尚未啟用的感應器。 若要判斷使用者在此案例中是否啟用任何感應器,您必須處理 ISensorEvents::OnStateChanged 事件。
// Get the sensor collection.
hr = pSensorManager->GetSensorsByType(SAMPLE_SENSOR_TYPE_TIME, &pSensorColl);
if(SUCCEEDED(hr))
{
// Request permissions for all sensors
// in the collection.
hr = pSensorManager->RequestPermissions(0, pSensorColl, FALSE);
}
您可以選擇先同步測試感應器狀態,再嘗試擷取資料。 下列範例程式碼示範這項技術。
if(SUCCEEDED(hr))
{
// Check the current sensor state.
SensorState state = SENSOR_STATE_NOT_AVAILABLE;
hr = pSensor->GetState(&state);
if(SUCCEEDED(hr))
{
if(state == SENSOR_STATE_ACCESS_DENIED)
{
wprintf_s(L"\nSensor not enabled, requesting permissions...\n");
hr = pSensorManager->RequestPermissions(0, pSensorColl, TRUE);
if(hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED) ||
hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))
{
wprintf_s(L"\nYou have previously denied access to this sensor.\n");
wprintf_s(L"Please use the Location and Other Sensors control panel\n");
wprintf_s(L"to enable the WDK Time Sensor and run this program again.\n");
}
}
}
}
if(SUCCEEDED(hr))
{
// Get the data report.
hr = pSensor->GetData(&pReport);
}
如果嘗試從特定感應器擷取資料包表失敗,下列範例程式碼會提示使用者輸入感應器許可權。
if(SUCCEEDED(hr))
{
// Get the data report.
hr = pSensor->GetData(&pReport);
if(E_ACCESSDENIED == hr)
{
wprintf_s(L"\nSensor not enabled, requesting permissions...\n");
hr = pSensorManager->RequestPermissions(0, pSensorColl, TRUE);
if(hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED) ||
hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))
{
wprintf_s(L"\nYou have previously denied access to this sensor.\n");
wprintf_s(L"Please use the Location and Other Sensors control panel\n");
wprintf_s(L"to enable the WDK Time Sensor and run this program again.\n");
}
}
}
相關主題
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應