如何实现手机向智能手表发送模板通知
=================

#### 问题现象

手机应用主动向穿戴设备推送模板通知，如何实现？

#### 背景知识

*   Wear Engine聚焦华为穿戴设备能力开放，目前提供了应用间消息通信（设备基础能力）等能力，参考：[开放能力](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/we-business_introduction#zh-cn_topic_0000001073786836_section0241143121313)。
*   接入前需要[申请接入Wear Engine服务](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/wearengine_apply)和[配置Client ID](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/configuration_client_id)。
*   [notify](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/wearengine_api#section087562072313)：向穿戴设备发送模板化通知。

#### 解决方案

获取已连接设备列表，从已连接设备列表中选定需要通信的设备，调用[wearEngine.getNotifyClient](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/wearengine_api#section552416431386)方法，获取[NotifyClient](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/wearengine_api#section82221754103913)对象并定义[NotificationOptions](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/wearengine_api#section0751457344)配置参数类，调用[notify](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/wearengine_api#section087562072313)方法，从手机上的应用发送通知到智能手表侧。

完整的代码示例如下：

import { wearEngine } from '@kit.WearEngine';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button('发送模板化通知')
        .onClick(() => {
        _  // 获取DeviceClient对象_
          try {
            let deviceClient: wearEngine.DeviceClient =
              wearEngine.getDeviceClient(this.getUIContext().getHostContext());
         _   // 创建一个设备列表用于存储返回的设备_
            let deviceList: wearEngine.Device\[\] = \[\];

          _  // 调用getConnectedDevices方法，查询用户是否有已连接的穿戴设备_
            deviceClient.getConnectedDevices().then(devices => {
            _  // 处理返回的设备列表_
              deviceList = devices;

              if (deviceList.length > 0) {
               _ // 从得到的设备列表中选取目标设备，并定义为device(假设数组中存在已连接设备且第一位即为目标设备)_
                let targetDevice: wearEngine.Device = deviceList\[0\];

               _ // 获取NotifyClient对象_
                let notifyClient: wearEngine.NotifyClient =
                  wearEngine.getNotifyClient(this.getUIContext().getHostContext());

               _ // 构造NotificationOptions对象_
                let button1: wearEngine.NotificationButton = {
                  buttonId: wearEngine.ButtonId.FIRST\_BUTTON,
                _  // 按钮内容最大长度为12字节_
                  content: '取消'
                };
                let button2: wearEngine.NotificationButton = {
                  buttonId: wearEngine.ButtonId.SECOND\_BUTTON,
                 _ // 按钮内容最大长度为12字节_
                  content: '确认'
                };
                let type1Notification: wearEngine.Notification = {
                  type: wearEngine.NotificationType.NOTIFICATION\_WITH\_TWO\_BUTTONS,
                  _// 包名与标题的最大长度为28字节_
                  bundleName: 'bundleName',
                  title: '模板通知',
                _  // 消息内容最大长度为400字节_
                  text: '来自手机端的模板通知',
                  buttons: \[button1, button2\]
                };
                let options: wearEngine.NotificationOptions = {
                  notification: type1Notification,
                  onAction: (feedback: wearEngine.NotificationFeedback) => {
                    console.info(\`one button notify get feedback is ${feedback.action ? feedback.action :
                      feedback.errorCode}\`);
                  }
                };

               _ // 发送模板化通知至设备侧_
                notifyClient.notify(targetDevice.randomId, options).then(result => {
                  console.info(\`Succeeded in sending notification. Result is ${result}\`);
                  this.getUIContext().getPromptAction().showToast({
                    message: \`Succeeded in sending notification\`,
                    duration: 2000,
                    showMode: promptAction.ToastShowMode.DEFAULT,
                    bottom: 80
                  });
                }).catch((error: BusinessError) => {
                  console.error(\`Failed to send notification. Code is ${error.code}, message is ${error.message}\`);
                });

              }
            }).catch((error: BusinessError) => {
           _   // 处理调用失败时捕获到的异常_
              console.error(\`Failed to get deviceList. Code is ${error.code}, message is ${error.message}\`);
            });
          } catch (error) {
            console.error(\`Failed to get deviceClient. Code is ${error.code}, message is ${error.message}\`);
          }

        });
    }.padding(20);
  }
}