欢迎加入开源鸿蒙PC社区:

欢迎在PC社区平台申请新建项目:

相应的跨平台框架仓库地址:https://atomgit.com/OpenHarmonyPCDeveloper

鸿蒙PC系统集成:通知、外部唤起与文件访问的边界

桌面应用和手机应用最大的差别,不是屏幕大小,而是“别人会不会来找你”。手机应用大多自己启动、自己退出;电脑上的应用要接文件、接协议、接通知,用户从文件管理器双击一个文件,或者从浏览器点一个链接,系统应该把你的应用叫起来,而不是让用户先找图标再手动打开。

Android 用 Intent,iOS 用 URL Scheme 加 UTI,H5 用自定义协议,Electron 用 app.setAsDefaultProtocolClient。鸿蒙PC这套东西叫 want,配合 skills.uris 声明能力边界。名字不同,思路相通,但鸿蒙PC把权限收得更紧,很多在 Android 上一个 <intent-filter> 就能解决的事,在这里要同时考虑沙箱、临时授权和上架配置。

这篇用一个完整页面把三条链路串起来:外部 URI 唤起、通知带 wantAgent 回跳、文件选择器拿到 URI 后直接读。代码在 MateBook 14(HarmonyOS 7.0.0.115 / API 26)上编译、安装、运行过,下面出现的界面都来自这台机器。

一、先让系统知道你能接什么

外部唤起的入口在 module.json5 的 skills 里。一个 Ability 可以挂多组 skill,第一组通常是桌面入口,第二组才是能力声明:

"skills": [
  {
    "entities": ["entity.system.home"],
    "actions": ["action.system.home"]
  },
  {
    "actions": ["ohos.want.action.viewData"],
    "uris": [
      {
        "scheme": "hpcdemo",
        "host": "open"
      }
    ]
  }
]

scheme 是必填的,没有它这条 uri 规则不成立;host 建议一起写,否则 hpcdemo://anything 都会进来,边界太松。actions 里的 ohos.want.action.viewData 表示“查看一份数据”,和文件、链接这类场景对得上。

配好之后,用 hdc 可以直接模拟外部调用:

hdc shell aa start -a EntryAbility -b com.example.fxharmony \
  -A ohos.want.action.viewData \
  -U "hpcdemo://open?from=filemanager&text=hello%20pc"

-U 传 URI,-A 传 action。少了 action,系统可能匹配不到这条 skill;少了 -U,want.uri 是空的。两个参数要一起给。

真机上跑出来的效果是这样:页面顶部状态变成“外部唤起已到达”,下面显示完整的 URI,并把 text 参数解析出来。

在这里插入图片描述

二、onCreate 和 onNewWant 都要接

外部唤起分两种情况:应用没启动,走 onCreate;应用已经在运行,走 onNewWant。只在 onCreate 里读 want.uri,用户第二次从文件管理器打开文件时,页面什么都不会变,因为 Ability 根本没重建。

我的做法是把 want.uri 统一写进 AppStorage,页面只认这一份状态:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    AppStorage.setOrCreate<string>('launchUri', want.uri ?? '');
  }

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    AppStorage.setOrCreate<string>('launchUri', want.uri ?? '');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.loadContent('pages/Index', (err: BusinessError) => {
      if (err.code) {
        hilog.error(0x0000, 'EntryAbility', 'loadContent failed: %{public}s', JSON.stringify(err));
      }
    });
  }
}

页面用 @StorageLink('launchUri') 接住。这样做的好处是页面不需要持有 Ability 引用,也不用在 onNewWant 里想办法通知页面刷新——状态自己会到。

有一个细节值得说:onNewWant 触发时,如果页面在后台或被最小化,系统通常会把窗口拉到前台。我的示例没有额外调 showWindow(),真机上从 hdc 触发时窗口会自己出现。不同版本对“是否自动前置”的处理可能不同,如果做正式产品,建议在 onNewWant 里显式检查窗口状态,必要时自己拉起。

三、通知:先要开关,再谈内容

通知这块,鸿蒙PC和手机基本一致:没有用户授权,publish 不会报错,但通知不会出现。所以第一步不是拼 NotificationRequest,而是确认开关。

if (!notificationManager.isNotificationEnabledSync()) {
  await notificationManager.requestEnableNotification(this.ctx());
}

requestEnableNotification 会弹系统对话框,用户点“允许”之后开关才真正打开。这个对话框是系统画的,应用改不了样式,也不该想着绕过。

在这里插入图片描述

授权通过后再发通知。下面这段是示例里的核心逻辑:

const info: wantAgent.WantAgentInfo = {
  wants: [
    {
      bundleName: this.ctx().abilityInfo.bundleName,
      abilityName: 'EntryAbility'
    }
  ],
  actionType: wantAgent.OperationType.START_ABILITY,
  requestCode: 100,
  actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
const agent = await wantAgent.getWantAgent(info);
const request: notificationManager.NotificationRequest = {
  id: 1001,
  notificationSlotType: notificationManager.SlotType.SERVICE_INFORMATION,
  content: {
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: {
      title: '鸿蒙PC 系统集成演示',
      text: '点这条通知会回到应用,并带上一条新的 want',
      additionalText: 'hpcdemo://open'
    }
  },
  wantAgent: agent
};
await notificationManager.publish(request);

notificationSlotType 我选了 SERVICE_INFORMATION,这是“服务信息”类,适合状态提醒;社交消息用 SOCIAL_COMMUNICATION,营销内容用 CONTENT_INFORMATION,选错类型会影响系统对通知的排序和打扰级别。wantAgent 决定点击通知后去哪,START_ABILITY 表示拉起一个 Ability,UPDATE_PRESENT_FLAG 让同 id 的通知更新已有那条,而不是堆一屏。

在这里插入图片描述

通知中心这张图里,标题和正文与代码里的字段一一对应。additionalText 只是给系统的一份补充信息,卡片上展不展开由系统决定,不要指望它承载关键内容。id 固定 1001,重复发布只会更新这一条,撤销也用同一个 id:

await notificationManager.cancel(1001);

很多教程只写 publish 不写 cancel,做出来的应用通知越积越多,用户只能去系统设置里关掉。通知是应用的声音,不是喇叭,用完要收。

四、文件访问:选择器给的 URI 可以直接读

文件这块,鸿蒙PC的规则比手机更明确:应用默认在自己的沙箱里,沙箱外的文件要通过 Picker 或用户授权进入。

DocumentViewPicker 负责文档类文件,PhotoViewPicker 负责媒体库。示例里选一个文本文件,拿到 URI 后直接用 fileIo 读:

const options = new picker.DocumentSelectOptions();
options.maxSelectNumber = 1;
const viewPicker = new picker.DocumentViewPicker(this.ctx());
const uris: string[] = await viewPicker.select(options);
const uri = uris[0];
const file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
const stat = fs.statSync(file.fd);
const buffer = new ArrayBuffer(1024);
const len = fs.readSync(file.fd, buffer);
fs.closeSync(file);
const decoder = util.TextDecoder.create('utf-8');
const text = decoder.decodeWithStream(new Uint8Array(buffer.slice(0, len)), { stream: false });

在这里插入图片描述

图里选的是用户目录下的一个 JSON 文件,页面显示的是真实 URI、文件大小和前 1KB 内容。这里没有申请任何存储权限,靠的是选择器返回的临时授权。

临时授权能撑多久,取决于系统策略和文件位置,不要把它当成永久权限。要长期访问某个目录,有两条路:一是在 select() 里传 authMode 和 defaultFilePathUri,引导用户到指定目录后再授权;二是申请持久化权限。两条路都比“直接拼一个绝对路径去读”靠谱。

还有一个容易忽略的能力:平板和电脑支持 3D 目录预授权,下载目录用 ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY,文档目录用 ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY。这两个权限不是普通应用随便声明的,属于受限权限,上架前要单独评估。我的建议是能用 Picker 就用 Picker,预授权只在“应用本身就是文件工具”时才值得。

五、完整页面代码

pages/Index.ets 全文如下。三个区块分别对应外部唤起、通知、文件访问,状态都放在页面里,不依赖全局单例:

import { common, wantAgent } from '@kit.AbilityKit';
import { notificationManager } from '@kit.NotificationKit';
import { picker, fileIo as fs } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @StorageLink('launchUri') launchUri: string = '';
  @State notifyState: string = '未检查通知权限';
  @State notifyEnabled: boolean = false;
  @State fileInfo: string = '还没有选择文件';
  @State filePreview: string = '';
  @State log: string = '';

  aboutToAppear(): void {
    this.notifyEnabled = notificationManager.isNotificationEnabledSync();
    this.notifyState = this.notifyEnabled ? '通知开关已打开' : '通知开关未打开';
  }

  private ctx(): common.UIAbilityContext {
    return getContext(this) as common.UIAbilityContext;
  }

  private queryValue(uri: string, key: string): string {
    const mark = uri.indexOf('?');
    if (mark < 0) {
      return '';
    }
    const pairs = uri.substring(mark + 1).split('&');
    for (let i = 0; i < pairs.length; i++) {
      const kv = pairs[i].split('=');
      if (kv.length === 2 && kv[0] === key) {
        return decodeURIComponent(kv[1]);
      }
    }
    return '';
  }

  private async enableNotification(): Promise<void> {
    try {
      await notificationManager.requestEnableNotification(this.ctx());
      this.notifyEnabled = notificationManager.isNotificationEnabledSync();
      this.notifyState = this.notifyEnabled ? '通知开关已打开' : '用户没有打开通知';
    } catch (e) {
      const err = e as BusinessError;
      this.notifyState = `申请失败:${err.code}`;
    }
  }

  private async publishNotification(): Promise<void> {
    try {
      if (!notificationManager.isNotificationEnabledSync()) {
        await notificationManager.requestEnableNotification(this.ctx());
      }
      const info: wantAgent.WantAgentInfo = {
        wants: [
          {
            bundleName: this.ctx().abilityInfo.bundleName,
            abilityName: 'EntryAbility'
          }
        ],
        actionType: wantAgent.OperationType.START_ABILITY,
        requestCode: 100,
        actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
      };
      const agent = await wantAgent.getWantAgent(info);
      const request: notificationManager.NotificationRequest = {
        id: 1001,
        notificationSlotType: notificationManager.SlotType.SERVICE_INFORMATION,
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: '鸿蒙PC 系统集成演示',
            text: '点这条通知会回到应用,并带上一条新的 want',
            additionalText: 'hpcdemo://open'
          }
        },
        wantAgent: agent
      };
      await notificationManager.publish(request);
      this.notifyEnabled = true;
      this.notifyState = '已发布通知 #1001,去通知中心看看';
      this.log = 'publish 成功,通知 id 1001';
    } catch (e) {
      const err = e as BusinessError;
      this.notifyState = `发布失败:${err.code}`;
      this.log = `publish 失败,code=${err.code}`;
    }
  }

  private async cancelNotification(): Promise<void> {
    try {
      await notificationManager.cancel(1001);
      this.notifyState = '已撤销通知 #1001';
    } catch (e) {
      const err = e as BusinessError;
      this.notifyState = `撤销失败:${err.code}`;
    }
  }

  private async pickFile(): Promise<void> {
    try {
      const options = new picker.DocumentSelectOptions();
      options.maxSelectNumber = 1;
      const viewPicker = new picker.DocumentViewPicker(this.ctx());
      const uris: string[] = await viewPicker.select(options);
      if (uris.length === 0) {
        this.fileInfo = '取消了选择';
        return;
      }
      const uri = uris[0];
      const file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
      const stat = fs.statSync(file.fd);
      const buffer = new ArrayBuffer(1024);
      const len = fs.readSync(file.fd, buffer);
      fs.closeSync(file);
      const decoder = util.TextDecoder.create('utf-8');
      const text = decoder.decodeWithStream(new Uint8Array(buffer.slice(0, len)), { stream: false });
      this.fileInfo = `${uri}\n${stat.size} 字节,临时授权可用`;
      this.filePreview = text;
      this.log = '选择器返回的 URI 已经可以直接读';
    } catch (e) {
      const err = e as BusinessError;
      this.fileInfo = `读取失败:${err.code}`;
      this.filePreview = '';
    }
  }

  @Builder
  SectionTitle(title: string, desc: string) {
    Column({ space: 4 }) {
      Text(title)
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .fontColor('#1A1A1A')
        .width('100%')
      Text(desc)
        .fontSize(12)
        .fontColor('#8A8A8E')
        .width('100%')
    }
    .width('100%')
    .alignItems(HorizontalAlign.Start)
  }

  build() {
    Column() {
      Row({ space: 10 }) {
        Text('鸿蒙PC 系统集成实验台')
          .fontSize(18)
          .fontWeight(FontWeight.Medium)
          .fontColor('#1A1A1A')
        Text('want / 通知 / 文件')
          .fontSize(12)
          .fontColor('#6B6B70')
          .backgroundColor('#F0F1F3')
          .padding({ left: 8, right: 8, top: 4, bottom: 4 })
          .borderRadius(4)
        Blank()
        Text(this.launchUri.length > 0 ? '外部唤起已到达' : '等待外部唤起')
          .fontSize(12)
          .fontColor(this.launchUri.length > 0 ? '#00A870' : '#8A8A8E')
      }
      .width('100%')
      .height(58)
      .padding({ left: 20, right: 20 })
      .backgroundColor(Color.White)

      Divider().color('#E5E6E8')

      Scroll() {
        Column({ space: 14 }) {
          Column({ space: 10 }) {
            this.SectionTitle('外部唤起', 'skills.uris 匹配到 hpcdemo://open 后,Ability 会收到新的 want')
            Text(this.launchUri.length > 0 ? this.launchUri : '还没有外部请求进来,可以用 aa start 带 -U 触发')
              .fontSize(12)
              .fontColor(this.launchUri.length > 0 ? '#0A59F7' : '#8A8A8E')
              .fontFamily('monospace')
              .width('100%')
              .padding(10)
              .backgroundColor('#F7F8FA')
              .borderRadius(6)
            Text(this.launchUri.length > 0
              ? `解析结果:text = ${this.queryValue(this.launchUri, 'text') || '(没有 text 参数)'}`
              : 'onCreate 与 onNewWant 都会把 want.uri 写进 AppStorage,页面只认这一份状态。')
              .fontSize(13)
              .fontColor('#3A3A3C')
              .width('100%')
          }
          .width('100%')
          .padding(16)
          .backgroundColor(Color.White)
          .borderRadius(10)

          Column({ space: 10 }) {
            this.SectionTitle('通知', '通知能不能发出去,先看开关,再看内容类型和 wantAgent')
            Row({ space: 8 }) {
              Text(this.notifyEnabled ? '已授权' : '未授权')
                .fontSize(12)
                .fontColor(this.notifyEnabled ? '#00A870' : '#D9485F')
                .backgroundColor(this.notifyEnabled ? '#E8F7EF' : '#FDEBEE')
                .padding({ left: 8, right: 8, top: 3, bottom: 3 })
                .borderRadius(4)
              Text(this.notifyState)
                .fontSize(12)
                .fontColor('#6B6B70')
                .layoutWeight(1)
            }
            .width('100%')

            Row({ space: 10 }) {
              Button('申请通知权限')
                .fontSize(13)
                .height(34)
                .backgroundColor('#F0F1F3')
                .fontColor('#1A1A1A')
                .onClick(() => {
                  this.enableNotification();
                })
              Button('发一条通知')
                .fontSize(13)
                .height(34)
                .backgroundColor('#0A59F7')
                .onClick(() => {
                  this.publishNotification();
                })
              Button('撤销')
                .fontSize(13)
                .height(34)
                .backgroundColor('#F0F1F3')
                .fontColor('#1A1A1A')
                .onClick(() => {
                  this.cancelNotification();
                })
            }
            .width('100%')

            Text('通知里带了 wantAgent,点击通知不是“打开应用”,而是把一条带参数的 want 送回 EntryAbility。')
              .fontSize(12)
              .fontColor('#8A8A8E')
              .width('100%')
          }
          .width('100%')
          .padding(16)
          .backgroundColor(Color.White)
          .borderRadius(10)

          Column({ space: 10 }) {
            this.SectionTitle('文件访问', '选择器给的是 file:// URI,读之前不用自己拼沙箱路径')
            Button('选择一个文本文件')
              .fontSize(13)
              .height(34)
              .backgroundColor('#F0F1F3')
              .fontColor('#1A1A1A')
              .onClick(() => {
                this.pickFile();
              })
            Text(this.fileInfo)
              .fontSize(12)
              .fontColor('#6B6B70')
              .fontFamily('monospace')
              .width('100%')
              .padding(10)
              .backgroundColor('#F7F8FA')
              .borderRadius(6)
            Text(this.filePreview.length > 0 ? this.filePreview : '选中文件后,这里显示前 1KB 内容。')
              .fontSize(13)
              .fontColor(this.filePreview.length > 0 ? '#1A1A1A' : '#B0B0B4')
              .lineHeight(20)
              .width('100%')
              .maxLines(8)
              .textOverflow({ overflow: TextOverflow.Ellipsis })
          }
          .width('100%')
          .padding(16)
          .backgroundColor(Color.White)
          .borderRadius(10)

          if (this.log.length > 0) {
            Text(this.log)
              .fontSize(11)
              .fontColor('#8A8A8E')
              .width('100%')
          }
        }
        .width('100%')
        .padding(20)
      }
      .width('100%')
      .layoutWeight(1)
      .scrollBar(BarState.Auto)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F2F3F5')
  }
}

六、上架和权限上的几个硬边界

第一条,exported 要开。外部应用或系统才能把你叫起来,module.json5 里 Ability 的 exported 设成 true 是前提。只配了 skills 没开 exported,aa start 会直接失败。

第二条,兼容分发不是默认。手机、平板应用上架时,要在 AGC 的基本信息里主动勾选“兼容分发到 PC/2in1 的 AppGallery”,应用才会以兼容模式出现在鸿蒙PC上。不勾就不会分发。想走原生窗口逻辑,则直接在支持设备里选 PC/2in1,系统不会把应用放进兼容模式。

第三条,受限权限不要硬闯。我试过给示例声明 ohos.permission.READ_PASTEBOARD,用调试证书安装时直接被拦下来。这类权限要走申请和 ACL 配置,不是写一行 requestPermissions 就能用。做系统集成时,凡是看到“受限”两个字,先确认自己的应用类型和上架渠道是否支持,再决定要不要用。

第四条,文件 URI 的授权是有范围的。Picker 给的是临时授权,能读当前这个文件;想读同目录的兄弟文件,得重新选或者申请目录授权。把 URI 存起来下次直接用,很可能失效。这个坑在文件管理器类应用里特别常见,正确做法是保存 URI 的同时保存授权状态,失效后重新引导用户选择。

系统集成做下来,我的感受是:鸿蒙PC把“能不能接”和“接了之后能做什么”分得很清楚。skills.uris 解决前者,Picker 和权限解决后者。把这两层分开想,代码不会乱,上架也不会卡在权限说明上。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐