精准碰一碰近场分享与拖拽投送实战:把文件“碰“进另一台设备【鸿蒙心迹】

本文详解HarmonyOS精准碰一碰(NearLink)近场分享能力的接入实践,涵盖设备能力探测、分享URI转换、MIME类型规范、大文件进度与续传、接收端声明及权限配置等关键环节。强调沙箱路径需转为content://URI、双方需亮屏靠近、传输依赖硬件支持等核心约束,适用于图片、短视频等小文件无感投送场景。

目录

一、背景与痛点

传文件最烦的是"先开 App、再选设备、再等配对"。HarmonyOS 的精准碰一碰(NearLink / 碰一碰分享)把这一步压缩成"两台设备靠近一碰,文件就过去了",配合拖拽投送还能把图直接拖进对方窗口。但真做接入,我遇到:设备不支持、距离太远拉不起、权限没配导致静默失败、大文件传输中断。

碰一碰底层是近场发现 + 近场传输,开发侧主要和分享意图(Want)+ 近场能力打交道。本文讲清接入链路与避坑。

二、能力与规格

维度说明
能力近场发现、近场分享、拖拽投送
依赖设备需支持 NearLink / 碰一碰硬件与系统版本
入口系统分享面板(Want sendData)+ 近场投送通道
约束距离近(厘米级)、需双方亮屏解锁、权限与可见性
典型场景图片/视频碰传、会议纪要投送、跨设备接力

三、核心代码(发起近场分享)

import { wantConstant } from '@kit.AbilityKit';
import { fileUri } from '@kit.CoreFileKit';
import { nearbyShare } from '@kit.NearLinkKit'; // 近场能力查询/传输

// 1. 把沙箱文件转成可分享 URI
function toShareUri(sandboxPath: string): string {
  return fileUri.getUriFromPath(sandboxPath); // 如 file://...
}

// 2. 能力探测:先确认设备支持碰一碰,避免按钮点了没反应
function isNearbySupported(): boolean {
  return nearbyShare.isSupported(); // 低端机/旧版本返回 false
}

// 3. 构造分享 Want,交给系统分享面板(碰一碰会在面板里出现)
function shareNearby(ctx: Context, filePath: string): void {
  if (!isNearbySupported()) {
    // 降级:走普通二维码/蓝牙分享
    fallbackShare(ctx, filePath);
    return;
  }
  const want: Want = {
    action: wantConstant.Action.sendData,
    type: 'image/jpeg',                 // MIME,决定接收方可识别
    uri: toShareUri(filePath),
    parameters: { 'ohos.extra.param.key_share_target': 'nearby' },
  };
  // 拉起系统分享,用户选"碰一碰/近场"即可近场发送
  (ctx as common.UIAbilityContext).startAbility(want)
    .catch(err => console.error('share failed', err));
}

// 4. 降级方案:二维码/蓝牙分享
function fallbackShare(ctx: Context, filePath: string): void {
  // 生成二维码或走蓝牙通道,保证功能可用
  console.info('device not support nearby, fallback to qrcode/bluetooth');
}

// 5. 大文件进度回调:监听传输进度,UI 上提示"保持设备靠近"
function watchProgress(taskId: string): void {
  nearbyShare.on('progress', (info: ProgressInfo) => {
    const percent = Math.round(info.transferred / info.total * 100);
    console.info(`transfer progress: ${percent}%`);
    // 更新 UI 进度条,并提示用户保持设备靠近
  });
  nearbyShare.on('interrupt', () => {
    console.warn('transfer interrupted, retry...');
    // 触发续传/重试逻辑
  });
}

四、实战要点

要点 1:先确认设备能力,别假设都支持。
碰一碰依赖硬件与系统版本,低端机/旧版本可能没有。发起前用能力查询判断,不支持就降级成普通二维码/蓝牙分享,别让按钮点了没反应。

要点 2:URI 必须用 getUriFromPath 转换。
直接塞沙箱绝对路径,接收方拿不到(跨应用沙箱隔离)。一定要转成 file:// 形式的分享 URI。

要点 3:MIME type 写准,否则接收端不认。
type 决定对方用什么打开。图片用 image/jpeg、视频 video/mp4,乱写会导致接收方无应用可处理,传输白做。

要点 4:大文件做好中断与进度。
近场传输受距离、干扰影响可能中断。大文件务必带进度回调与续传/重试,并在 UI 上明示"保持设备靠近",别让用户以为卡死了。

五、进阶:接收端与权限配置

碰一碰是双向的,发送端只是链路的一半。接收端要能"接住"文件,还需要做好三件事:

1. 声明接收能力(module.json5)

接收方要在 module.json5 里声明 sendData 的 want 过滤,否则系统分享面板不会把文件投给它:

{
  "abilities": [
    {
      "name": "ReceiveAbility",
      "skills": [
        {
          "actions": ["ohos.want.action.sendData"],
          "uris": [
            { "scheme": "file", "type": "image/*" },
            { "scheme": "file", "type": "video/*" }
          ]
        }
      ]
    }
  ]
}

2. 在 onNewWant 里接收文件

import { fileUri } from '@kit.CoreFileKit';

export default class ReceiveAbility extends UIAbility {
  onNewWant(want: Want): void {
    const uri = want.uri; // file:// 形式的分享 URI
    if (!uri) return;
    // 转回沙箱路径并落盘
    const sandboxPath = fileUri.getPathFromUri(uri);
    console.info(`received file at: ${sandboxPath}`);
    // 通知 UI 展示接收结果
  }
}

3. 权限与可见性

  • 双方需亮屏解锁,且开启"碰一碰/近场分享"开关;
  • 首次使用会弹权限确认,务必在 UI 上引导用户授权;
  • 距离过远(超过厘米级)会拉不起,UI 上要提示"请将设备靠近"。

六、小结与边界

碰一碰适合小文件快速近场投送(图片、短视频、纪要),是"无感分享"的典范。它强依赖硬件与近距离,不适合大体积离线同步。落地记住:能力先探测、URI 要转换、MIME 写准、大文件带进度、接收端要声明。发送与接收两端都配好,链路才算完整。


本文为原创首发实战笔记,基于 HarmonyOS 近场分享/碰一碰能力,代码示例为调用范式示意,实际接口以华为官方文档为准。

七、总结

本文围绕 HarmonyOS 精准碰一碰(NearLink)近场分享能力,梳理了从背景痛点、能力规格、核心代码到实战要点的完整接入链路。核心收获可归纳为四点:

  • 能力先探测:发起前确认设备是否支持 NearLink / 碰一碰,不支持时降级为二维码或蓝牙分享,避免按钮无响应。
  • URI 要转换:沙箱绝对路径无法跨应用传递,必须用 getUriFromPath 转成 file:// 分享 URI。
  • MIME 写准:type 决定接收端如何打开文件,图片用 image/jpeg、视频用 video/mp4,写错会导致接收方无应用可处理。
  • 大文件带进度:近场传输易受距离与干扰影响,务必提供进度回调、续传/重试,并在 UI 上提示"保持设备靠近"。

碰一碰适合小文件快速近场投送(图片、短视频、纪要),是无感分享的典范;但它强依赖硬件与近距离,不适合大体积离线同步。落地时按上述四点逐一核对,即可显著降低接入失败率。

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值