鸿蒙应用示例:API功能集成示例及注意事项

时间:2024-10-04 21:53:37

鸿蒙应用示例:API功能集成示例及注意事项_鸿蒙


【demo源码】:https://gitcode.com/zhongcongxu01/harmony_demo/overview

这个示例应用展示了如何集成以下功能:

  1. 获取设备的AAID(应用唯一标识符)。
  2. 启动短信应用并预填联系人信息。
  3. 启动浏览器并加载指定网页。
  4. 启动应用市场中的应用详情页面。
  5. 启动设备的设置界面(如WLAN设置、输入法设置等)。
  6. 拨打电话。
  7. 启动扫码界面。
  8. 检测指定应用是否已安装。
  9. 获取当前应用的信息。
  10. 获取设备的基本信息。
  11. 开启或关闭窗口隐私模式(防截屏录屏)。
  12. 监听网络连接状态。
  13. 获取当前设备的网络连接属性(如IP地址)。
  14. 启动相机选择器。
  15. 从相册选择图片。
  16. 设置应用的屏幕方向(竖屏或横屏)。
  17. 检测当前应用的屏幕方向。
  18. 获取当前设备类型。

【注意事项】

1、设备唯一标识 AAID(应用匿名标识符)

• 实测结果:当用户主动卸载应用后重新安装时,AAID值会发生变化。
• 建议:如果希望卸载应用后仍保持唯一标识符不变,可以考虑使用第三方库如harmony-utils来实现这一功能。

2、开启或关闭窗口隐私模式(防截屏录屏)

• 防截屏效果:当用户尝试截屏时,会有提示“当前页面涉及隐私内容,不允许截屏”。
• 防录屏效果:当设置防截屏录屏后,录屏时涉及到设置防录屏的页面将显示为黑屏,从而达到防录屏的效果。

3、判断API是否可用,使用canIUse方法的场景

在开发过程中,经常会出现以下警告:

The API is not supported on all devices. Use the canIUse condition to determine whether the API is supported.

鸿蒙应用示例:API功能集成示例及注意事项_API_02

这通常出现在某些API文档或IDE的提示信息中,表明该API并不是所有设备都支持。此时,我们需要使用canIUse方法来动态判断当前设备是否支持该API。

具体操作步骤如下:

(1). 查看API文档:首先查看API文档,确定该API是否支持所有设备。
(2). IDE提示信息:在IDE中编写代码时,如果IDE提示“该API不是所有设备都支持”,则需要使用canIUse方法。
(3). 查找@syscap值:在API文档中查找对应的@syscap值,例如SystemCapability.Window.SessionManager。
(4). 编写条件判断:在代码中使用canIUse方法,传入找到的@syscap值来判断当前设备是否支持该API。

示例代码: 假设我们要使用call.makeCall方法拨打电话,但在某些设备上可能不支持该功能,那么我们可以这样写

if (canIUse('SystemCapability.Telephony.Call')) {
  call.makeCall("13800000000", (err: BusinessError) => {
    if (err) {
      console.error(`makeCall fail, err->${JSON.stringify(err)}`);
    } else {
      console.log(`makeCall success`);
    }
  });
} else {
  promptAction.showToast({
    message: `当前设备不支持拨打电话功能`,
    duration: 2000,
    bottom: '500lpx'
  });
}

在这个例子中,SystemCapability.Telephony.Call是拨打电话功能所需的系统能力。通过canIUse方法判断当前设备是否支持该能力,从而决定是否调用call.makeCall方法。

4、核心代码

import { bundleManager, common, Want } from '@kit.AbilityKit';
import { BusinessError, deviceInfo } from '@kit.BasicServicesKit';
import { call } from '@kit.TelephonyKit';
import { scanBarcode, scanCore } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { promptAction, window } from '@kit.ArkUI';
import { connection } from '@kit.NetworkKit';
import { camera, cameraPicker } from '@kit.CameraKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { resourceManager } from '@kit.LocalizationKit';
import { AAID } from '@kit.PushKit';

function getMmsWant() {
  let want: Want = {
    bundleName: 'com.ohos.mms',
    abilityName: 'com.ohos.mms.MainAbility',
    parameters: {
      contactObjects: JSON.stringify([{ "contactsName": 'ZhangSan', "telephone": "16888880000" }]),
      content: "短信内容测试321",
      pageFlag: 'conversation'
    }
  };
  return want
}

function getBrowsableWant() {
  let want: Want = {
    action: 'ohos.want.action.viewData',
    entities: ['entity.system.browsable'],
    uri: 'https://www.huawei.com'
  };
  return want
}

function getAppGalleryDetailWant() {
  let bundleName = "com.amap.hmapp"
  let want: Want = {
    action: 'ohos.want.action.appdetail',
    uri: 'store://appgallery.huawei.com/app/detail?id=' + bundleName, //  bundleName为需要打开应用详情的应用的包名
  };
  return want
}

function getWifiEntryWant() {
  let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: 'wifi_entry'  // 根据”设置”应用配置的界面信息,选择不同的uri
  };
  return want
}


function getSetInputWant() {
  let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: 'set_input'  // 根据”设置”应用配置的界面信息,选择不同的uri
  };
  return want
}


function getLocationManagerSettingsWant() {
  let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: 'location_manager_settings'  // 根据”设置”应用配置的界面信息,选择不同的uri
  };
  return want
}

function makeCall() {
  if (canIUse("SystemCapability.Applications.Contacts")) {
    call.makeCall("13800000000", (err: BusinessError) => {
      if (err) {
        console.error(`makeCall fail, err->${JSON.stringify(err)}`);
      } else {
        console.log(`makeCall success`);
      }
    });
  } else {
    promptAction.showToast({
      message: `当前设备不支持该功能`,
      duration: 2000,
      bottom: '500lpx'
    });
  }
}

function scanCode(context: common.UIAbilityContext) {
  if (canIUse('SystemCapability.Multimedia.Scan.ScanBarcode')) {
    if (canIUse('SystemCapability.Multimedia.Scan.Core')) {
      // 定义扫码参数options
      let options: scanBarcode.ScanOptions = {
        scanTypes: [scanCore.ScanType.ALL],
        enableMultiMode: true,
        enableAlbum: true
      };
      // 可调用getContext接口获取当前页面关联的UIAbilityContext
      scanBarcode.startScanForResult(context, options,
        (error: BusinessError, result: scanBarcode.ScanResult) => {
          if (error) {
            hilog.error(0x0001, '[Scan CPSample]',
              `Failed to get ScanResult by callback with options. Code: ${error.code}, message: ${error.message}`);
            return;
          }
          // 收到扫码结果后返回
          hilog.info(0x0001, '[Scan CPSample]',
            `Succeeded in getting ScanResult by callback with options, result is ${JSON.stringify(result)}`);
          promptAction.showToast({
            message: `扫码结果:${JSON.stringify(result)}`,
            duration: 2000,
            bottom: '500lpx'
          });
        })
      return
    }
  }
  promptAction.showToast({
    message: `当前设备不支持该功能`,
    duration: 2000,
    bottom: '500lpx'
  });
}

function checkApp() {
  try {
    let link: string = "amapuri://"
    let appName: string = "高德地图"
    let data = bundleManager.canOpenLink(link);
    hilog.info(0x0000, 'testTag', 'canOpenLink successfully: %{public}s', JSON.stringify(data));
    if (data) {
      promptAction.showToast({
        message: `${appName} APP 已安装`,
        duration: 2000,
        bottom: '500lpx'
      });
    } else {
      promptAction.showToast({
        message: `${appName} APP 未安装`,
        duration: 2000,
        bottom: '500lpx'
      });
    }
  } catch (err) {
    if (err['code'] == 17700056) {
      /*{
      "module": {
        "querySchemes": [
          "amapuri",
        ],*/
      promptAction.showToast({
        message: '请在src/main/module.json5配置link,参考注释 querySchemes',
        duration: 2000,
        bottom: '500lpx'
      });
    } else {
      promptAction.showToast({
        message: '未知异常',
        duration: 2000,
        bottom: '500lpx'
      });
    }
    let message = (err as BusinessError).message;
    hilog.error(0x0000, 'testTag', 'canOpenLink failed: %{public}s', message);
  }
}

function getAppInfo() {
  let bundleFlags =
    bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION |
    bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA;
  let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags)

  console.info('bundleInfo', JSON.stringify(bundleInfo))
  let sheets: SheetInfo[] = []
  Object.keys(bundleInfo).forEach((key: string) => {
    sheets.push({
      title: `${key}:${JSON.stringify(bundleInfo[key])}`,
      action: () => {
      }
    })
  })
  ActionSheet.show({
    title: '当前应用信息',
    subtitle: '',
    message: '',
    autoCancel: true,
    confirm: {
      defaultFocus: true,
      value: 'Confirm button',
      action: () => {
        console.log('Get Alert Dialog handled')
      }
    },
    cancel: () => {
      console.log('actionSheet canceled')
    },
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -10 },
    sheets: sheets
  })
}

function getDeviceInfo() {
  ActionSheet.show({
    title: '当前设备信息',
    subtitle: '',
    message: '',
    autoCancel: true,
    confirm: {
      defaultFocus: true,
      value: 'Confirm button',
      action: () => {
        console.log('Get Alert Dialog handled')
      }
    },
    cancel: () => {
      console.log('actionSheet canceled')
    },
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -10 },
    sheets: [
      {
        title: '设备品牌名称:' + deviceInfo.brand,
        action: () => {
        }
      },
      {
        title: '产品版本:' + deviceInfo.displayVersion,
        action: () => {
        }
      },
      {
        title: '系统版本:' + deviceInfo.osFullName,
        action: () => {
        }
      },
      {
        title: '系统软件API版本:' + deviceInfo.sdkApiVersion,
        action: () => {
        }
      },
      {
        title: '首个版本系统软件API版本:' + deviceInfo.firstApiVersion,
        action: () => {
        }
      },
      {
        title: '构建时间:' + deviceInfo.buildTime,
        action: () => {
        }
      },
      {
        title: '发行版系统api版本:' + deviceInfo.distributionOSApiVersion,
        action: () => {
        }
      },
    ]
  })
}

async function setWindowPrivacyModeTrue(context: common.UIAbilityContext) {
  let windowClass: window.Window = await window.getLastWindow(context)
  try {
    windowClass.setWindowPrivacyMode(true, (err: BusinessError) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
        if (errCode == 201) {
          /*
          {
            "module": {
              "requestPermissions": [
                {
                  "name": "ohos.permission.INTERNET"
                }
              ],*/
          promptAction.showToast({
            message: `请在src/main/module.json5添加权限 "name": "ohos.permission.PRIVACY_WINDOW"`,
            duration: 2000,
            bottom: '500lpx'
          });
        }
        return;
      }
      promptAction.showToast({
        message: `已开启 防截屏录屏`,
        duration: 2000,
        bottom: '500lpx'
      });
      console.info('Succeeded in setting the window to privacy mode.');
    });
  } catch (exception) {
    console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
  }
}

async function setWindowPrivacyModeFalse(context: common.UIAbilityContext) {
  let windowClass: window.Window = await window.getLastWindow(context)
  try {
    windowClass.setWindowPrivacyMode(false, (err: BusinessError) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
        if (errCode == 201) {

          promptAction.showToast({
            message: `请在src/main/module.json5添加权限 "name": "ohos.permission.PRIVACY_WINDOW"`,
            duration: 2000,
            bottom: '500lpx'
          });
        }
        return;
      }
      promptAction.showToast({
        message: `已关闭 防截屏录屏`,
        duration: 2000,
        bottom: '500lpx'
      });
      console.info('Succeeded in setting the window to privacy mode.');
    });
  } catch (exception) {
    console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
  }
}

function netConnectionListener() {
  let netCon: connection.NetConnection = connection.createNetConnection();
  // 先使用register接口注册订阅事件
  netCon.register((error: BusinessError) => {
    console.log(JSON.stringify(error));
    if (error) {
      if (error.code == 201) {
        promptAction.showToast({
          message: `请在src/main/module.json5添加权限 "name": "ohos.permission.GET_NETWORK_INFO"`,
          duration: 2000,
          bottom: '500lpx'
        });
      } else {
        promptAction.showToast({
          message: `${JSON.stringify(error)}`,
          duration: 2000,
          bottom: '500lpx'
        });
      }
      return;
    }
    promptAction.showToast({
      message: `已开启 网络状态监听`,
      duration: 2000,
      bottom: '500lpx'
    });
  });
  // 订阅网络丢失事件。调用register后,才能接收到此事件通知
  netCon.on('netLost', (data: connection.NetHandle) => {
    console.info("Succeeded to get data: netLost " + JSON.stringify(data));
    promptAction.showToast({
      message: `已关闭 网络`,
      duration: 2000,
      bottom: '500lpx'
    });
  });
  // 订阅网络能力变化事件。调用register后,才能接收到此事件通知
  netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
    console.info("Succeeded to get data: netConnectionPropertiesChange " + JSON.stringify(data));
    promptAction.showToast({
      message: `已开启 网络`,
      duration: 2000,
      bottom: '500lpx'
    });
  });
}

async function startCameraPicker(context: common.UIAbilityContext) {
  try {
    let pickerProfile: cameraPicker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
    };
    let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(context,
      [cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile);
    console.log("the pick pickerResult is:" + JSON.stringify(pickerResult)); //拍照结果
    if (pickerResult.resultCode == 0) {
      context.eventHub.emit("updateImage", pickerResult.resultUri)
    }
  } catch (error) {
    let err = error as BusinessError;
    console.error(`the pick call failed. error code: ${err.code}`);
  }
}

function selectPhoto(context: common.UIAbilityContext) {
  try {
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
      if (PhotoSelectResult.photoUris?.[0]) {
        context.eventHub.emit("updateImage", PhotoSelectResult.photoUris?.[0])
      }
    }).catch((err: BusinessError) => {
      console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
  }
}

function setAppLandscapeOrientation() {
  window.getLastWindow(getContext()).then((windowClass) => {
    windowClass.setPreferredOrientation(window.Orientation.PORTRAIT)
  })
}

function setAppPortraitOrientation() {
  window.getLastWindow(getContext()).then((windowClass) => {
    windowClass.setPreferredOrientation(window.Orientation.LANDSCAPE)
  })
}

function detectAppOrientation() {
  promptAction.showToast({
    message: getContext().resourceManager.getConfigurationSync().direction ===
    resourceManager.Direction.DIRECTION_VERTICAL ?
      "竖屏" : "横屏"
  })
}

function getDeviceType() {
  let getDeviceTypeInfo = () => {
    let
      deviceType = getContext().resourceManager.getDeviceCapabilitySync().deviceType;
    switch (deviceType) {
      case resourceManager.DeviceType.DEVICE_TYPE_PHONE:
        return "手机";
      case resourceManager.DeviceType.DEVICE_TYPE_TABLET:
        return "平板";
      case resourceManager.DeviceType.DEVICE_TYPE_PC:
        return "电脑";
      case resourceManager.DeviceType.DEVICE_TYPE_TV:
        return "电视";
      case resourceManager.DeviceType.DEVICE_TYPE_CAR:
        return "汽车";
      case resourceManager.DeviceType.DEVICE_TYPE_WEARABLE:
        return "穿戴";
      case resourceManager.DeviceType.DEVICE_TYPE_2IN1:
        return "2IN1";
      default:
        return "未知"
    }
  }
  promptAction.showToast({
    message: getDeviceTypeInfo()
  })
}

function getDefaultNet() {
  let isDefaultNet = connection.hasDefaultNetSync();
  promptAction.showToast({
    message: `当前${isDefaultNet ? '有网络' : '无网络'}`
  })
}

function getConnectionProperties() {
  connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
    connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => {
      if (error) {
        console.error(`Failed to get connection properties. Code:${error.code}, message:${error.message}`);
        return;
      }
      console.info("Succeeded to get data: " + JSON.stringify(data));
      try {
        let ip = data['linkAddresses'][0]['address']['address']
        console.info('本地ip:', ip)
        promptAction.showToast({
          message: `当前ip:${ip}`
        })
      } catch (e) {
        console.error("e", JSON.stringify(e));

      }

    })
  });

}

function getAAID() {
  AAID.getAAID().then((data: string) => {
    ActionSheet.show({
      title: '当前AAID',
      subtitle: `${data}`,
      message: `实测当用户主动卸载APP后重新安装时,AAID值会改变。`,
      autoCancel: true,
      confirm: {
        defaultFocus: true,
        value: 'Confirm button',
        action: () => {
          console.log('Get Alert Dialog handled')
        }
      },
      cancel: () => {
        console.log('actionSheet canceled')
      },
      alignment: DialogAlignment.Bottom,
      offset: { dx: 0, dy: -10 },
      sheets: [
        {
          title: '如果希望卸载APP后依旧不变,建议使用第三方harmony-utils',
          action: () => {
          }
        }
      ]
    })
    hilog.info(0x0000, 'testTag', 'Get AAID successfully: %{public}s', data);
  }).catch((err: BusinessError) => {
    hilog.error(0x0000, 'testTag', 'Get AAID failed: %{public}d %{public}s', err.code, err.message);
  });
}

class Item {
  key: string
  want: Want | Function

  constructor(key: string, want: Want | Function) {
    this.key = key
    this.want = want
  }
}

//拉起功能示例
@Entry
@Component
struct Index {
  @State array: Item[] = []
  @State imageUrl: string | undefined = undefined

  aboutToAppear(): void {

    getContext(this).eventHub.on('updateImage', (data: string) => {
      this.imageUrl = data
      console.info('imageUrl', this.imageUrl)
    })

    this.array.push(new Item('获取设备的AAID', getAAID))
    this.array.push(new Item('拉起短信界面并指定联系人', getMmsWant()))
    this.array.push(new Item('拉起浏览器并打开指定网页', getBrowsableWant()))
    this.array.push(new Item('拉起应用市场对应的应用详情界面', getAppGalleryDetailWant()))
    this.array.push(new Item('拉起设置应用HOME-WLAN界面', getWifiEntryWant()))
    this.array.push(new Item('拉起HOME-系统和更新-输入法页面', getSetInputWant()))
    this.array.push(new Item('拉起开启定位的设置页', getLocationManagerSettingsWant()))
    this.array.push(new Item('拉起拨号界面并显示待拨出的号码', makeCall))
    this.array.push(new Item('拉起扫码页面', scanCode))
    this.array.push(new Item('判断是否安装了某个APP', checkApp))
    this.array.push(new Item('获取应用信息', getAppInfo))
    this.array.push(new Item('获取设备信息', getDeviceInfo))
    this.array.push(new Item('开启防截屏录屏', setWindowPrivacyModeTrue))
    this.array.push(new Item('关闭防截屏录屏', setWindowPrivacyModeFalse))
    this.array.push(new Item('开启网络状态监听', netConnectionListener))
    this.array.push(new Item('判断当前网络链接状态', getDefaultNet))
    this.array.push(new Item('获取手机当前连接wifi的本机ip', getConnectionProperties))
    this.array.push(new Item('拉起相机', startCameraPicker))
    this.array.push(new Item('拉起相册', selectPhoto))
    this.array.push(new Item('设置当前app以竖屏方式显示', setAppLandscapeOrientation))
    this.array.push(new Item('设置当前app以横屏方式显示', setAppPortraitOrientation))
    this.array.push(new Item('判断APP是横屏还是竖屏', detectAppOrientation))
    this.array.push(new Item('获取当前设备类型', getDeviceType))


  }

  build() {
    Stack() {
      Scroll() {
        Column({ space: 5 }) {
          ForEach(this.array, (item: Item, index: number) => {
            Button(`【${index + 1}】${item.key}`).onClick(() => {
              if (item.want instanceof Function) {
                item.want(getContext(this))
              } else {
                const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
                context.startAbility(item.want).then(() => {
                  console.info('Start successfully.');
                }).catch((err: BusinessError) => {
                  console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
                });
              }
            })
          })
        }
      }
      .align(Alignment.Top)
      .width('100%')
      .height('100%')

      if (this.imageUrl) {
        Stack() {
          Image(this.imageUrl)
            .width('300lpx')
            .height('300lpx')
            .borderRadius(30)
        }.width('100%').height('100%').backgroundColor("#80000000").onClick(() => {
          this.imageUrl = undefined
        })
      }
    }.width('100%').height('100%')
  }
}