我的UWP应用程序的清单已经要求获得该许可。但是,有时候(可能是因为Windows 1809)似乎没有自动授予。相反,用户需要从控制面板打开应用程序的高级选项并进行设置。
那么有没有办法检查应用程序是否具有权限以通知用户?
这就是我的意思:设置>应用>(点击应用)>点击“高级选项”。另请注意,某些应用可能不需要任何权限,因此您可能看不到任何权限。查看MS天气应用程序,它需要两个权限。
这是我到目前为止找到的最佳解决方案:
private async Task<StorageLibrary> TryAccessLibraryAsync(KnownLibraryId library)
{
try
{
return await StorageLibrary.GetLibraryAsync(library);
}
catch (UnauthorizedAccessException)
{
//inform user about missing permission and ask to grant it
MessageDialog requestPermissionDialog =
new MessageDialog($"The app needs to access the {library}. " +
"Press OK to open system settings and give this app permission. " +
"If the app closes, please reopen it afterwards. " +
"If you Cancel, the app will have limited functionality only.");
var okCommand = new UICommand("OK");
requestPermissionDialog.Commands.Add(okCommand);
var cancelCommand = new UICommand("Cancel");
requestPermissionDialog.Commands.Add(cancelCommand);
requestPermissionDialog.DefaultCommandIndex = 0;
requestPermissionDialog.CancelCommandIndex = 1;
var requestPermissionResult = await requestPermissionDialog.ShowAsync();
if (requestPermissionResult == cancelCommand)
{
//user chose to Cancel, app will not have permission
return null;
}
//open app settings to allow users to give us permission
await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
//confirmation dialog to retry
var confirmationDialog = new MessageDialog(
$"Please give this app the {library} permission.");
confirmationDialog.Commands.Add(okCommand);
await confirmationDialog.ShowAsync();
//retry
return await TryAccessLibraryAsync(library);
}
}
这样做是因为它首先尝试通过其KnownLibraryId
获取给定的库。如果用户删除了应用程序的权限,那么它将失败并使用UnauthorizedAccessException
。
现在我们向用户展示一个解释问题的MessageDialog
,并要求他给予应用程序许可。
如果用户按下取消,该方法将返回null
,因为用户未授予我们许可。
否则,我们使用特殊启动URI ms-settings:appsfeatures-app
启动设置(请参阅docs),该页面将打开具有权限切换的应用高级设置页面。
现在这是一个不幸的问题 - 我发现更改权限将迫使当前关闭应用程序。我在第一个对话框中告知用户这个事实。如果将来这种情况发生变化,代码已经为这个替代方案做好了准备 - 显示了一个新的对话框,用户可以在更改权限时确认它,并且该方法将递归调用自身并尝试再次访问该库。
当然,我建议在应用程序关闭之前保存用户的数据,因为权限更改,以便在重新打开时,数据将保持不变,用户的流程不会中断。
如果您真的依赖此权限来实现其功能,也可以在应用程序启动后立即调用此权限。这样你就知道你有权访问,或者用户会在开头就给它正确,所以应用程序将被终止是没有害处的。
更新:我发现这个问题非常有趣,所以我有written a blogpost about it。