鸿蒙学习实战之路-Share Kit系列(16/17)-隔空传送与可信任设备
最近好多朋友问我:“西兰花啊,我想实现隔空传送功能,但不知道代码怎么写?” 害,这问题可问对人了!今天这篇,我就手把手带你实现隔空传送与可信任设备功能,从零到一,全程不超过 10 分钟(不含调试时间)~
鸿蒙学习实战之路-Share Kit系列(16/17)-隔空传送与可信任设备
最近好多朋友问我:“西兰花啊,我想实现隔空传送功能,但不知道代码怎么写?” 害,这问题可问对人了!
今天这篇,我就手把手带你实现隔空传送与可信任设备功能,从零到一,全程不超过 10 分钟(不含调试时间)~
隔空传算是啥?
隔空传送就是不接触设备,直接将内容传送到附近的设备。比如:
- 你在手机上看到一张好照片,想传到附近的平板上查看
- 你在平板上看到一篇文章,想传到附近的手机上阅读
这就像前端的 AirDrop,只不过 Share Kit 是系统级别的服务,体验更统一。
可信任设备是啥?
可信任设备就是你信任的设备,可以自动接收分享内容。比如:
- 你的手机、平板、电脑都登录了同一个华为账号
- 这些设备之间可以自动接收分享内容,不需要手动确认
这就像前端的自动同步,只不过 Share Kit 是系统级别的服务,体验更统一。
需要申请权限吗?
是的,隔空传送需要申请 ohos.permission.DISTRIBUTED_DATASYNC 权限。
配置权限
在 module.json5 中声明权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
🥦 西兰花警告:
我有个朋友忘记申请权限,结果隔空传送一直不成功,debug 了两小时才发现是权限问题!血泪教训啊朋友们!
完整实现步骤
实现隔空传送与可信任设备,就三步:
- 申请权限:在
module.json5中声明权限 - 获取可信任设备列表:使用
deviceManager模块获取可信任设备列表 - 隔空传送到指定设备:使用
systemShare模块隔空传送到指定设备
步骤 1:申请权限
在 module.json5 中声明 ohos.permission.DISTRIBUTED_DATASYNC 权限。
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
步骤 2:获取可信任设备列表
使用 deviceManager 模块获取可信任设备列表。
import { deviceManager } from '@kit.DistributedDeviceKit';
// 获取可信任设备列表
deviceManager.getTrustedDeviceList((err, data) => {
if (err) {
console.error(`获取可信任设备列表失败:${err}`);
return;
}
console.log(`可信任设备列表:${data}`);
});
步骤 3:隔空传送到指定设备
使用 systemShare 模块隔空传送到指定设备。
import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';
// 隔空传送到指定设备
function airDropToDevice(deviceId: string) {
// 构造分享数据
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: 'general.text',
uri: 'file://.../xxx.txt',
title: '隔空传送',
description: '这是一段隔空传送文本'
});
// 构建分享控制器
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
// 显示分享面板
let uiContext: UIContext = this.getUIContext();
let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
controller.show(context, {
previewMode: systemShare.SharePreviewMode.DEFAULT,
selectionMode: systemShare.SelectionMode.SINGLE,
targetDeviceId: deviceId
});
}
完整代码示例
把上面的步骤整合起来,就是一个完整的隔空传送与可信任设备的实现:
import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';
import { deviceManager } from '@kit.DistributedDeviceKit';
@Entry
@Component
struct AirDropPage {
// 分享文本
shareText: string = '这是一段隔空传送文本';
// 可信任设备列表
trustedDeviceList: Array<{ deviceId: string, deviceName: string }> = [];
aboutToAppear() {
// 获取可信任设备列表
this.getTrustedDeviceList();
}
// 获取可信任设备列表
getTrustedDeviceList() {
deviceManager.getTrustedDeviceList((err, data) => {
if (err) {
console.error(`获取可信任设备列表失败:${err}`);
return;
}
this.trustedDeviceList = data.map(device => {
return {
deviceId: device.deviceId,
deviceName: device.deviceName
};
});
});
}
// 隔空传送到指定设备
airDropToDevice(deviceId: string) {
// 构造分享数据
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: 'general.text',
uri: 'file://.../xxx.txt',
title: '隔空传送',
description: this.shareText
});
// 构建分享控制器
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
// 显示分享面板
let uiContext: UIContext = this.getUIContext();
let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
controller.show(context, {
previewMode: systemShare.SharePreviewMode.DEFAULT,
selectionMode: systemShare.SelectionMode.SINGLE,
targetDeviceId: deviceId
});
}
build() {
Column() {
Text('隔空传送示例')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.margin(20)
.fontColor(Color.Black);
Text(this.shareText)
.fontSize(16)
.margin({ left: 20, right: 20, bottom: 20 })
.fontColor(Color.Gray);
if (this.trustedDeviceList.length > 0) {
Text('选择设备:')
.fontSize(16)
.margin(20)
.fontColor(Color.Black);
ForEach(this.trustedDeviceList, (device: { deviceId: string, deviceName: string }) => {
Button(device.deviceName)
.onClick(() => {
this.airDropToDevice(device.deviceId);
})
.margin(10);
});
} else {
Text('暂无可信任设备')
.fontSize(16)
.margin(20)
.fontColor(Color.Gray);
}
}
.width('100%')
.height('100%');
}
}
在实际项目中怎么用?
上面的代码是基础实现,但在实际项目中,你可能会这样用:
示例:隔空传送图片
import { common } from '@kit.AbilityKit';
import { systemShare } from '@kit.ShareKit';
import { deviceManager } from '@kit.DistributedDeviceKit';
@Entry
@Component
struct AirDropImagePage {
// 分享图片
shareImage: string = 'file://.../xxx.jpg';
// 可信任设备列表
trustedDeviceList: Array<{ deviceId: string, deviceName: string }> = [];
aboutToAppear() {
// 获取可信任设备列表
this.getTrustedDeviceList();
}
// 获取可信任设备列表
getTrustedDeviceList() {
deviceManager.getTrustedDeviceList((err, data) => {
if (err) {
console.error(`获取可信任设备列表失败:${err}`);
return;
}
this.trustedDeviceList = data.map(device => {
return {
deviceId: device.deviceId,
deviceName: device.deviceName
};
});
});
}
// 隔空传送到指定设备
airDropToDevice(deviceId: string) {
// 构造分享数据
let shareData: systemShare.SharedData = new systemShare.SharedData({
utd: 'general.image',
uri: this.shareImage,
title: '隔空传送图片',
preview: this.shareImage,
description: '这是一张隔空传送的图片'
});
// 构建分享控制器
let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
// 显示分享面板
let uiContext: UIContext = this.getUIContext();
let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
controller.show(context, {
previewMode: systemShare.SharePreviewMode.DEFAULT,
selectionMode: systemShare.SelectionMode.SINGLE,
targetDeviceId: deviceId
});
}
build() {
Column() {
Text('隔空传送图片示例')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.margin(20)
.fontColor(Color.Black);
Image(this.shareImage)
.width(200)
.height(200)
.margin(20);
if (this.trustedDeviceList.length > 0) {
Text('选择设备:')
.fontSize(16)
.margin(20)
.fontColor(Color.Black);
ForEach(this.trustedDeviceList, (device: { deviceId: string, deviceName: string }) => {
Button(device.deviceName)
.onClick(() => {
this.airDropToDevice(device.deviceId);
})
.margin(10);
});
} else {
Text('暂无可信任设备')
.fontSize(16)
.margin(20)
.fontColor(Color.Gray);
}
}
.width('100%')
.height('100%');
}
}
常见问题
Q1:隔空传送不成功怎么办?
检查以下几点:
-
是否申请了权限:
- 确认是否在 module.json5 中声明了
ohos.permission.DISTRIBUTED_DATASYNC权限 - 确认用户是否授权了该权限
- 确认是否在 module.json5 中声明了
-
设备是否在同一网络:
- 确认设备是否在同一网络
- 确认设备是否支持隔空传送
-
设备是否已信任:
- 确认设备是否已添加到可信任设备列表
- 确认设备是否在线
Q2:如何添加设备到可信任列表?
在设备的设置中,找到"分布式设备管理",添加设备到可信任列表。
Q3:如何判断设备是否支持隔空传送?
可以通过 deviceManager.getTrustedDeviceList 获取可信任设备列表,然后检查设备类型:
deviceManager.getTrustedDeviceList((err, data) => {
if (err) {
console.error(`获取可信任设备列表失败:${err}`);
return;
}
data.forEach(device => {
if (device.deviceType === 'PHONE' || device.deviceType === 'TABLET' || device.deviceType === 'PC') {
console.log(`支持隔空传送的设备:${device.deviceName}`);
}
});
});
下一步学什么?
看完这篇,你应该已经能实现隔空传送与可信任设备了。接下来可以深入学习:
- 常见问题:分享失败、数据类型不支持等问题的解决方案
推荐资料
📚 官方文档:
我是盐焗西兰花,
不教理论,只给你能跑的代码和避坑指南。
下期见!🥦
更多推荐



所有评论(0)