鸿蒙开发实战往期文章必看:
一分钟了解”纯血版!鸿蒙HarmonyOS Next应用开发!
“非常详细的” 鸿蒙HarmonyOS Next应用开发学习路线!(从零基础入门到精通)
“一杯冰美式的时间” 了解鸿蒙HarmonyOS Next应用开发路径!
跨设备互通提供跨设备的相机、扫描、图库访问能力,平板或2in1设备可以调用手机的相机、扫描、图库等功能。
场景介绍
通过此能力实现跨设备交互,可以使用其他设备的相机、扫描和图库功能。
约束与限制
需同时满足以下条件,才能使用该功能:
- 设备限制
- 本端设备:HarmonyOS版本为HarmonyOS NEXT(4.0)及以上的平板或2in1设备。
- 远端设备:HarmonyOS版本为HarmonyOS NEXT(4.0)及以上、具有相机能力的手机或平板设备。
- 使用限制
- 双端设备需要登录同一华为账号。
- 双端设备需要打开WLAN和蓝牙开关。
条件允许时,建议双端设备接入同一个局域网,可提升唤醒相机的速度。
接口说明
在开发具体功能前,请先查阅参考文档。
接口名 | 描述 |
---|---|
获取跨设备互通可用的设备信息。 | |
拉起跨设备互通能力。 | |
取消跨设备互通能力。 |
开发步骤
1.引入头文件
#include "service_collaboration/service_collaboration_api.h"
2.编写CMakeList.txt
find_library(
# Sets the name of the path variable.
service_collaboration-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
libservice_collaboration_ndk.z.so
)
target_link_libraries(entry PUBLIC
${service_collaboration-lib}
)
3.编写Code调用接口
#include "service_collaboration/service_collaboration_api.h"
#include <thread>
static int32_t OnEventProc(ServiceCollaborationEventCode code, uint32_t extraCode)
{
return 0;
}
static int32_t OnDataCallbackProc(
ServiceCollaborationEventCode code, ServiceCollaborationDataType dataType, uint32_t dataSize, char* data)
{
return 0;
}
int main(int argc, char* argv[])
{
int two = 2;
int three = 3;
int filter = 1;
const int size = 3;
int shouldCancel = 0;
// 构建所需跨设备互通能力,并调用HMS_ServiceCollaboration_GetCollaborationDeviceInfos接口获取设备信息
ServiceCollaborationFilterType serviceFileterTypes[size] = {TAKE_PHOTO, SCAN_DOCUMENT, IMAGE_PICKER};
ServiceCollaboration_CollaborationDeviceInfoSets* info = HMS_ServiceCollaboration_GetCollaborationDeviceInfos(3, serviceFileterTypes);
// 构建callback回调
ServiceCollaboration_SelectInfo taskInfo = { TAKE_PHOTO, { 0 } };
for (uint32_t i = 0; i < info->size; i++) {
ServiceCollaboration_CollaborationDeviceInfo *deviceInfo =
(ServiceCollaboration_CollaborationDeviceInfo *)&(info->deviceInfoSets[i]);
if (filter == 1) {
taskInfo.serviceFilterType = TAKE_PHOTO;
}
if (filter == two) {
taskInfo.serviceFilterType = SCAN_DOCUMENT;
}
if (filter == three) {
taskInfo.serviceFilterType = IMAGE_PICKER;
}
std::memcpy(taskInfo.deviceNetworkId, deviceInfo->deviceNetworkId, COLLABORATIONDEVICEINFO_DEVICENETWORKID_MAXLENGTH-1);
}
ServiceCollaborationCallback callback = {.OnEvent = OnEventProc, .OnDataCallback = OnDataCallbackProc};
// 传入拍照参数、callback回调并调用HMS_ServiceCollaboration_StartCollaboration接口
uint32_t id = HMS_ServiceCollaboration_StartCollaboration(&taskInfo, &callback);
std::this_thread::sleep_for(std::chrono::seconds(three));
if (shouldCancel) {
// 三秒后主动调用HMS_ServiceCollaboration_StopCollaboration关闭跨设备互通
int32_t ret = HMS_ServiceCollaboration_StopCollaboration(id);
}
}