app.bluetooth - 蓝牙 API
查询蓝牙状态、枚举已配对/已连接设备并监听蓝牙事件。
权限: L2 敏感级,需要系统蓝牙权限。首次调用时系统会弹出授权提示。
方法
app.bluetooth.isEnabled()
检查蓝牙是否已开启。
返回值: boolean
if app.bluetooth.isEnabled() then
app.log.info("蓝牙已开启")
end
app.bluetooth.pairedDevices()
获取所有已配对的蓝牙设备列表。
返回值: array<table> - 每项包含:
name(string) - 设备名称address(string) - 设备地址isConnected(boolean) - 是否当前已连接
local devices = app.bluetooth.pairedDevices()
for _, d in ipairs(devices) do
local status = d.isConnected and "已连接" or "未连接"
app.log.info(d.name .. " (" .. d.address .. "): " .. status)
end
app.bluetooth.connectedDevices()
获取当前已连接的蓝牙设备列表。
返回值: array<table> - 每项包含:
name(string) - 设备名称address(string) - 设备地址
local devices = app.bluetooth.connectedDevices()
app.log.info("已连接设备数: " .. #devices)
for _, d in ipairs(devices) do
app.log.info(d.name .. " - " .. d.address)
end
app.bluetooth.watch(event, callback)
监听蓝牙设备事件。
参数:
event(string) - 事件名称:"deviceConnected"- 设备连接时触发"deviceDisconnected"- 设备断开时触发
callback(function) - 回调函数,接收事件表:name(string) - 设备名称address(string) - 设备地址
返回值: string, error - watcher 句柄 ID
local handle, err = app.bluetooth.watch("deviceConnected", function(e)
app.notification.show("蓝牙", e.name .. " 已连接")
end)
local handle2 = app.bluetooth.watch("deviceDisconnected", function(e)
app.log.info("设备断开: " .. e.name)
end)
app.bluetooth.stopAllWatchers()
停止当前插件注册的所有蓝牙监听器。
返回值: boolean
app.bluetooth.stopAllWatchers()
app.bluetooth.listWatchers()
列出当前插件已注册的蓝牙监听器。
返回值: array<table> - 每项包含:
id(string) - watcher 句柄 IDevent(string) - 监听的事件名称
local watchers = app.bluetooth.listWatchers()
for _, w in ipairs(watchers) do
app.log.info(w.id .. " -> " .. w.event)
end
说明
- 蓝牙 API 需要系统蓝牙权限,首次调用时将提示用户授权
pairedDevices()返回所有已配对设备(无论是否当前连接)connectedDevices()仅返回当前活跃连接的设备watch()返回的句柄在插件卸载时自动清理,无需手动调用stopAllWatchers()- 蓝牙事件在后台线程触发,回调中避免执行耗时操作
示例
监控耳机连接状态
function MyPlugin:onLoad()
app.bluetooth.watch("deviceConnected", function(e)
-- 仅关注耳机类设备
if e.name:find("AirPods") or e.name:find("Headphone") then
app.audio.setVolume(0.5)
app.notification.show("耳机已连接", e.name .. " - 音量已自动调整")
end
end)
app.bluetooth.watch("deviceDisconnected", function(e)
if e.name:find("AirPods") or e.name:find("Headphone") then
app.notification.show("耳机已断开", e.name)
end
end)
end
列出蓝牙设备信息
function MyPlugin:handleBluetoothInfo(context)
if not app.bluetooth.isEnabled() then
app.dialog.alert("蓝牙", "蓝牙未开启")
return
end
local paired = app.bluetooth.pairedDevices()
local connected = app.bluetooth.connectedDevices()
local lines = {
"蓝牙设备信息",
"已配对: " .. #paired .. " 台,已连接: " .. #connected .. " 台",
"",
}
for _, d in ipairs(paired) do
local status = d.isConnected and "[已连接]" or "[未连接]"
table.insert(lines, status .. " " .. d.name)
end
app.dialog.alert("蓝牙设备", table.concat(lines, "\n"))
end