PhoneLineTransportDevice调用报错:系统拒绝访问原因排查
我正在使用PhoneLineTransportDevice API在Windows与OPPO F11 Pro手机间建立HFP和SCO蓝牙连接,以实现PC端接打电话功能。以下是我的代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.Calls; using Windows.Devices.Enumeration; namespace PhoneLinetransportdevice { internal class Program { static async Task Main(string[] args) { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(PhoneLineTransportDevice.GetDeviceSelector(PhoneLineTransport.Bluetooth)); for (int i = 0; i < devices.Count; i++) { if (devices[i].Name== "OPPO F11 Pro") { Console.WriteLine(i + "#: " + devices[i].Name); var PDevice = PhoneLineTransportDevice.FromId(devices[i].Id); var result = await PDevice.RequestAccessAsync(); if (!PDevice.IsRegistered()) { PDevice.RegisterApp(); } var flag = await PDevice.ConnectAsync(); if (flag) { Console.WriteLine("Connected"); } else { Console.WriteLine("Could not connect to PhoneLineDevice"); } } } } } }
调用var result = await PDevice.RequestAccessAsync();时被系统拒绝,该API并未过时,却抛出如下异常:
未处理的异常: System.UnauthorizedAccessException: 访问被拒绝。(来自HRESULT的异常: 0x80070005 (E_ACCESSDENIED))
在 Windows.ApplicationModel.Calls.PhoneLineTransportDevice.RegisterApp()
在 PhoneLinetransportdevice.Program.d__0.MoveNext() 位置 C:\StudioApps\PhoneLinetransportdevice\PhoneLinetransportdevice\Program.cs:行号 25
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
在 System.Runtime.CompilerServices.TaskAwaiter.GetResult()
在 PhoneLinetransportdevice.Program.(String[] args)
请问出现该权限拒绝错误的原因是什么?
导致权限拒绝错误的原因主要有以下几点:
应用类型不兼容:
PhoneLineTransportDeviceAPI仅支持UWP(通用Windows平台)应用,你当前使用的是控制台应用,这类传统桌面应用无法适配UWP的权限模型,无法获取该API所需的系统权限。缺失必需的功能声明:即便是UWP应用,也需要在
Package.appxmanifest中声明相关权限才能调用该API,必须添加的功能包括:phoneCall:授予应用访问电话功能的权限bluetooth:授予应用访问蓝牙设备的权限
未添加这些声明时,系统会直接拒绝权限请求。
未处理权限请求结果:你调用了
RequestAccessAsync但未判断返回的PhoneLineTransportDeviceAccessStatus值。如果返回状态为Denied或DeniedBySystem,此时继续执行RegisterApp()必然会触发权限异常。正确流程是先检查返回状态,仅当状态为Allowed时再执行后续操作。系统或设备端限制:Windows系统中若已有其他应用占用该蓝牙设备的HFP通道,或蓝牙服务未正常运行,会导致权限被拒;此外OPPO F11 Pro手机端需要确认配对权限,允许PC端访问通话功能,否则也会引发连接失败。
内容的提问来源于stack exchange,提问作者Aryaveer Chaudhary

