core
    正在准备搜索索引...

    接口 Ymx

    ymx Core

    interface Ymx {
        coreVersionCode: number;
        coreVersionName: string;
        inApp: boolean;
        isAndroid: boolean;
        isHarmony: boolean;
        isIos: boolean;
        isWeb: boolean;
        versionCode: number;
        versionName: string;
        abortNetworkTask(task: NetworkTask): Promise<void>;
        arrayBufferToBase64(buffer: Uint8Array): string;
        base64ToArrayBuffer(base64: string): Uint8Array;
        canHandle(data: LaunchData): Promise<boolean>;
        chooseContact(): Promise<ChooseContactResult>;
        chooseMedia(data: ChooseMediaData): Promise<ChooseMediaResult>;
        clearLayouts(): Promise<void>;
        clearStorage(): Promise<void>;
        close(result?: any): Promise<void>;
        compressImage(data: CompressImageData): Promise<CompressImageResult>;
        compressVideo(data: CompressVideoData): Promise<CompressVideoResult>;
        detectCode(data: DetectCodeData): Promise<CodeResult[]>;
        downloadFile(data: DownloadFileData): Promise<DownloadFileResult>;
        emit(data: EmitData): Promise<void>;
        exit(): Promise<void>;
        getBadgeNumber(): Promise<BadgeNumber>;
        getBatteryInfo(): Promise<GetBatteryInfoResult>;
        getClipboardData(): Promise<ClipboardData>;
        getDatabaseManager(): YmxDatabaseManager;
        getDeclaredPermissions(): Promise<DeclaredPermissionsResult>;
        getDeviceInfo(): Promise<DeviceInfoResult>;
        getFileSystemManager(): YmxFileSystemManager;
        getImageInfo(data: GetImageInfoData): Promise<GetImageInfoResult>;
        getKeepScreenOn(): Promise<KeepScreenOnResult>;
        getLaunchParams(): Promise<LaunchParamsResult>;
        getLayout(): Promise<Layout>;
        getLayouts(): Promise<LayoutPattern[]>;
        getNavigationBar(): Promise<NavigationBar>;
        getScreenBrightness(): Promise<ScreenBrightness>;
        getScreenOrientation(): Promise<ScreenOrientation>;
        getSignatureInfo(): Promise<SignatureInfoResult>;
        getStatusBar(): Promise<StatusBar>;
        getStorage(data: StorageKey): Promise<StorageResult>;
        getStorageInfo(): Promise<StorageInfoResult>;
        getTheme(): Promise<Theme>;
        getTitleBar(): Promise<TitleBar>;
        getVideoInfo(data: GetVideoInfoData): Promise<GetVideoInfoResult>;
        getWindowInfo(): Promise<WindowInfoResult>;
        hasPermissionDeclared(
            permission: PermissionData,
        ): Promise<PermissionDeclaredResult>;
        hasPermissionGranted(permission: PermissionData): Promise<PermissionResult>;
        hideLoading(): Promise<void>;
        hideToast(): Promise<void>;
        insertLayout(layoutPatternIndex: LayoutPatternIndex): Promise<void>;
        isNotificationEnabled(): Promise<NotificationEnabledResult>;
        isSupportAccelerometer(): Promise<boolean>;
        isSupportCompass(): Promise<boolean>;
        isSupportGyroscope(): Promise<boolean>;
        launch(data: LaunchData): Promise<void>;
        makePhoneCall(data: MakePhoneCallData): Promise<void>;
        off(data: UnsubscribeEvent): Promise<void>;
        offAccelerometerChange(listener?: Function): Promise<void>;
        offAppHide(listener?: () => void): Promise<void>;
        offAppShow(listener?: () => void): Promise<void>;
        offCompassChange(listener?: Function): Promise<void>;
        offGyroscopeChange(listener?: Function): Promise<void>;
        on(data: SubscribeEvent): Promise<void>;
        onAccelerometerChange(
            listener: (res: AccelerometerResult) => void,
        ): Promise<void>;
        onAppHide(listener: () => void): Promise<void>;
        onAppShow(listener: () => void): Promise<void>;
        once(data: SubscribeEvent): Promise<void>;
        onCompassChange(listener: (res: CompassResult) => void): Promise<void>;
        onConfirmPrivacy(listener: (isAgreed: boolean) => void): Promise<void>;
        onGyroscopeChange(listener: (res: GyroscopeResult) => void): Promise<void>;
        open(data: OpenData): Promise<void>;
        openNetworkSettings(): Promise<void>;
        openNotificationSettings(): Promise<void>;
        openPermissionSetting(
            permissions: PermissionsData,
        ): Promise<PermissionsResult>;
        removeLayout(index: number): Promise<void>;
        removeStorage(data: StorageKey): Promise<void>;
        request(data: RequestData): Promise<RequestResult>;
        requestEnableNotification(): Promise<void>;
        requestPermission(
            permission: RequestPermissionData,
        ): Promise<PermissionResult>;
        requestPermissions(
            permissions: RequestPermissionsData,
        ): Promise<PermissionsResult>;
        requirePlugin(pluginId: string): object;
        saveImageToPhotosAlbum(data: SaveMediaToPhotosAlbumData): Promise<void>;
        saveVideoToPhotosAlbum(data: SaveMediaToPhotosAlbumData): Promise<void>;
        scanCode(data: ScanCodeData): Promise<CodeResult>;
        sendSms(data: SendSmsData): Promise<void>;
        setBadgeNumber(data: BadgeNumber): Promise<void>;
        setClipboardData(data: ClipboardData): Promise<void>;
        setKeepScreenOn(data: KeepScreenOnData): Promise<void>;
        setLayout(layout: Layout): Promise<void>;
        setNavigationBar(navigationBar: NavigationBar): Promise<void>;
        setScreenBrightness(data: ScreenBrightness): Promise<void>;
        setScreenOrientation(screenOrientation: ScreenOrientation): Promise<void>;
        setStatusBar(statusBar: StatusBar): Promise<void>;
        setStorage(data: StorageData): Promise<void>;
        setTheme(theme: Theme): Promise<void>;
        setTitleBar(titleBar: TitleBar): Promise<void>;
        showActionSheet(data: ShowActionSheetData): Promise<ShowActionSheetResult>;
        showLoading(data: ShowLoadingData): Promise<void>;
        showModal(data: ShowModalData): Promise<ShowModalResult>;
        showToast(data: ShowToastData): Promise<void>;
        startAccelerometer(data: AccelerometerData): Promise<void>;
        startCompass(data: CompassData): Promise<void>;
        startGyroscope(data: GyroscopeData): Promise<void>;
        stopAccelerometer(): Promise<void>;
        stopCompass(): Promise<void>;
        stopGyroscope(): Promise<void>;
        systemShare(data: SystemShareData): Promise<void>;
        uploadFile(data: UploadFileData): Promise<UploadFileResult>;
        vibrateLong(): Promise<void>;
        vibrateShort(data: VibrateShortData): Promise<void>;
        viewImages(data: ViewImagesData): Promise<void>;
    }

    层级 (查看层级一览)

    索引
    abortNetworkTask arrayBufferToBase64 base64ToArrayBuffer canHandle chooseContact chooseMedia clearLayouts clearStorage close compressImage compressVideo detectCode downloadFile emit exit getBadgeNumber getBatteryInfo getClipboardData getDatabaseManager getDeclaredPermissions getDeviceInfo getFileSystemManager getImageInfo getKeepScreenOn getLaunchParams getLayout getLayouts getNavigationBar getScreenBrightness getScreenOrientation getSignatureInfo getStatusBar getStorage getStorageInfo getTheme getTitleBar getVideoInfo getWindowInfo hasPermissionDeclared hasPermissionGranted hideLoading hideToast insertLayout isNotificationEnabled isSupportAccelerometer isSupportCompass isSupportGyroscope launch makePhoneCall off offAccelerometerChange offAppHide offAppShow offCompassChange offGyroscopeChange on onAccelerometerChange onAppHide onAppShow once onCompassChange onConfirmPrivacy onGyroscopeChange open openNetworkSettings openNotificationSettings openPermissionSetting removeLayout removeStorage request requestEnableNotification requestPermission requestPermissions requirePlugin saveImageToPhotosAlbum saveVideoToPhotosAlbum scanCode sendSms setBadgeNumber setClipboardData setKeepScreenOn setLayout setNavigationBar setScreenBrightness setScreenOrientation setStatusBar setStorage setTheme setTitleBar showActionSheet showLoading showModal showToast startAccelerometer startCompass startGyroscope stopAccelerometer stopCompass stopGyroscope systemShare uploadFile vibrateLong vibrateShort viewImages
    coreVersionCode: number

    基础库版本号,如 2608200

    coreVersionName: string

    基础库版本名,如 1.260820.0

    inApp: boolean

    是否运行在 APP 环境中

    isAndroid: boolean

    是否运行在 Android APP 环境中

    isHarmony: boolean

    是否运行在 HarmonyOS APP 环境中

    isIos: boolean

    是否运行在 iOS APP 环境中

    isWeb: boolean

    是否运行在浏览器环境中

    versionCode: number

    APP 版本号,如 123

    versionName: string

    APP 版本名,如 1.2.3

    • 取消(中断)网络任务

      let downloadTask;
      await ymx.downloadFile({
      url: 'https://www.yimenapp.com/doc/doc.pdf',
      filePath: 'fs://file/my/doc.pdf',
      onNetworkTaskCreated(task) {
      console.log('task', task);
      downloadTask = task;
      },
      async onDataReceiveProgress(progress) {
      console.log(`共需接收 ${progress.totalSize} Bytes,已接收 ${progress.receiveSize} Bytes`);
      //下载超过 30KB 就取消,仅作为接口调用示例展示。
      if (downloadTask && (progress.receiveSize > 30 * 1024)) {
      await ymx.abortNetworkTask(downloadTask);
      }
      }
      });

      参数

      返回 Promise<void>

    • 同步方法,将 ArrayBuffer 对象转成 Base64 字符串

      参数

      • buffer: Uint8Array

      返回 string

    • 同步方法,将 Base64 字符串转成 ArrayBuffer 对象

      参数

      • base64: string

      返回 Uint8Array

    • 是否可以处理指定的 uri,主要用于检测是否已安装对应的 App。

      • 仅能检测在 query schemes 中已注册的 url scheme,未注册返回 false。
      • 与 launch 接口不同,如 launch weixin:// 不要求注册 weixin scheme,只要安装了微信客户端即可拉起。

      参数

      返回 Promise<boolean>

      true 可以处理 url, false 不可以

    • 拍摄或从手机相册中选择图片或视频

      参数

      返回 Promise<ChooseMediaResult>

      await ymx.chooseMedia({
      // 相册
      sourceType: ['album'],
      // 选一个
      count: 1,
      // 图片
      mediaType: ['image']
      });

      await ymx.chooseMedia({
      // 拍照
      sourceType: ['camera'],
      // 后置摄像头
      camera: 'back',
      mediaType: ['image']
      });

      await ymx.chooseMedia({
      // 拍照
      sourceType: ['camera'],
      // 前置摄像头
      camera: 'front',
      // 视频
      mediaType: ['video']
      });
    • 清空布局规则

      返回 Promise<void>

    • 清理本地数据缓存

      返回 Promise<void>

      await ymx.clearStorage();
      
    • 关闭当前窗口

      参数

      • 可选result: any

        需要返回给父窗口的数据

      返回 Promise<void>

      ymx.close()
      .then(() => {
      console.log('成功');
      })
      .catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
      ymx.close({
      hello: 'world 世界',
      year: 2026
      }).then(() => {
      console.log('成功');
      }).catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
    • 压缩图片,可选压缩质量。

      参数

      返回 Promise<CompressImageResult>

      //从相册选图
      const choose = await ymx.chooseMedia({
      mediaType: ['image'],
      count: 1
      });
      //压缩图片
      const newImage = await ymx.compressImage({
      src: choose.tempFiles[0].tempFilePath,
      quality: 85,
      compressedWidth: 720
      });
      //获取新的图片信息
      await ymx.getImageInfo({
      src: newImage.tempFilePath
      });
    • 压缩视频,可指定压缩质量 quality 进行压缩。

      参数

      返回 Promise<CompressVideoResult>

      //从相册选视频
      const choose = await ymx.chooseMedia({
      mediaType: ['video'],
      count: 1
      });
      //压缩视频
      await ymx.compressVideo({
      src: choose.tempFiles[0].tempFilePath,
      quality: 'medium',
      filePath: 'fs://temp/video.mp4'
      });
    • 识别图片中的二维码、条码,返回结果数组。

      参数

      返回 Promise<CodeResult[]>

      //放一个 id 为 htmlFileInput 文件选择标签到页面上,<input type="file" accept="image/*" id="htmlFileInput" />
      const htmlFileInput = document.getElementById('htmlFileInput');
      if (htmlFileInput.files.length > 0) {
      const reader = new FileReader();
      reader.onload = function(event) {
      const buffer = new Uint8Array(event.target.result);
      //识别
      ymx.detectCode({
      imageData: buffer
      })
      .then(res => {
      alert(JSON.stringify(res));
      })
      .catch(err => {
      alert(JSON.stringify(err));
      });
      };
      reader.onerror = function() {
      alert('读取文件失败');
      };
      //读取文件
      const file = htmlFileInput.files[0];
      reader.readAsArrayBuffer(file);
      } else {
      alert("请选择文件");
      }
      //本地临时文件
      const localFile = 'fs://temp/img.png';
      try {
      //下载图片
      await ymx.downloadFile({
      url: 'https://www.yimenapp.com/assets/img/qr-test.png',
      filePath: localFile
      });
      //识别
      const res = await ymx.detectCode({
      filePath: localFile
      });
      alert(JSON.stringify(res));
      } catch (err) {
      alert(err.message);
      } finally {
      //删除临时文件
      const fs = ymx.getFileSystemManager();
      if (await fs.exist({ path: localFile })) {
      await fs.remove({ path: localFile });
      }
      }
    • 下载文件

      参数

      返回 Promise<DownloadFileResult>

      await ymx.downloadFile({
      url: 'https://www.yimenapp.com/doc/doc.pdf'
      });

      //下载保存到指定的文件路径
      await ymx.downloadFile({
      url: 'https://www.yimenapp.com/doc/doc.pdf',
      filePath: 'fs://file/my/doc.pdf'
      });

      //本地临时图片文件路径
      const imageFile = 'fs://temp/img.jpg';
      try {
      //下载图片
      await ymx.downloadFile({
      url: 'https://i.yimenyun.net/sys/2.jpg',
      filePath: imageFile,
      onNetworkTaskCreated(task) {
      console.log('download task', task);
      },
      onDataReceiveProgress: (progress) => {
      console.log(`总共 ${progress.totalSize} Bytes,已下载 ${progress.receiveSize} Bytes`);
      }
      });
      alert('已下载,即将保存到相册。');
      //保存到相册
      await ymx.saveImageToPhotosAlbum({
      filePath: imageFile
      });
      alert('已保存到相册');
      } catch (err) {
      alert(err.message);
      } finally {
      //删除临时文件
      const fs = ymx.getFileSystemManager();
      if (await fs.exist({ path: imageFile })) {
      await fs.remove({ path: imageFile });
      }
      }
    • 触发一个事件

      参数

      返回 Promise<void>

      await ymx.emit({
      eventName: 'my-event',
      data: 'hello event'
      });
      await ymx.emit({
      eventName: 'my-once',
      data: 'hello once'
      });
    • 退出应用

      返回 Promise<void>

      await ymx.exit();
      
    • 获取基于 URL 正则匹配模式的 UI 布局规则列表

      按顺序匹配 url,使用成功匹配项的 layout 设置,如果全部匹配失败则使用最后一项配置。

      返回 Promise<LayoutPattern[]>

    • 隐藏 loading 提示

      返回 Promise<void>

      await ymx.hideLoading();
      
    • 隐藏吐司提示

      返回 Promise<void>

      await ymx.hideToast();
      
    • 检测设备是否支持加速计

      返回 Promise<boolean>

      const isSupport = await ymx.isSupportAccelerometer();
      alert(isSupport ? '支持' : '不支持');
    • 检测设备是否支持罗盘

      返回 Promise<boolean>

      const isSupport = await ymx.isSupportCompass();
      alert(isSupport ? '支持' : '不支持');
    • 检测设备是否支持陀螺仪

      返回 Promise<boolean>

      const isSupport = await ymx.isSupportGyroscope();
      alert(isSupport ? '支持' : '不支持');
    • 拉起第三方应用,不要求在 query schemes 中注册 url scheme,只要安装了对应应用即可拉起。

      参数

      返回 Promise<void>

      ymx.launch({
      // 使用外部统浏览器(一般为系统默认浏览器)打开网页
      uri: 'https://xw.qq.com/'
      }).then(() => {
      console.log('成功');
      }).catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
      ymx.launch({
      // 拉起微信
      uri: 'weixin://'
      }).then(() => {
      console.log('成功');
      }).catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
      ymx.launch({
      // 拉起电话拨号
      uri: 'tel://1801234'
      }).then(() => {
      console.log('成功');
      }).catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
    • 取消订阅监听

      参数

      返回 Promise<void>

      // 移除 my-event 的所有监听器
      await ymx.off({
      eventName: 'my-event'
      });
    • 移除加速计数据事件的监听函数,不传 listener 则移除所有监听函数

      参数

      • 可选listener: Function

      返回 Promise<void>

      //移除全部加速计监听器
      await ymx.offAccelerometerChange();
    • 移除应用切换到后台监听器

      参数

      • 可选listener: () => void

        提供了 listener 则仅移除此监听器,为提供 listener 则全部移除

      返回 Promise<void>

      // 移除所有切换到后台的监听器
      await ymx.offAppHide();
    • 移除应用切换到前台监听器

      参数

      • 可选listener: () => void

        提供了 listener 则仅移除此监听器,为提供 listener 则全部移除

      返回 Promise<void>

      // 移除所有切换到前台的监听器
      await ymx.offAppShow();
    • 移除罗盘数据事件的监听函数,不传 listener 则移除所有监听函数

      参数

      • 可选listener: Function

      返回 Promise<void>

      //移除全部罗盘监听器
      await ymx.offCompassChange();
    • 移除陀螺仪数据事件的监听函数,不传 listener 则移除所有监听函数

      参数

      • 可选listener: Function

      返回 Promise<void>

      //移除全部陀螺仪监听器
      await ymx.offGyroscopeChange();
    • 持续订阅监听一个事件

      参数

      返回 Promise<void>

      await ymx.on({
      eventName: 'my-event',
      listener: (data) => {
      console.log('event data', data);
      }
      });
    • 监听加速计数据事件

      参数

      返回 Promise<void>

      await ymx.onAccelerometerChange((res) => {
      console.log(`Accelerometer x:${res.x}, y:${res.y}, z:${res.z}`);
      });
    • 订阅应用切换到后台时触发事件,如果 App 处于后台则立即触发监听器。

      参数

      • listener: () => void

      返回 Promise<void>

      监听器

      await ymx.onAppHide(() => {
      console.log('appHide');
      });
    • 订阅应用切换到前台时触发事件,如果 App 处于前台激活状态则立即触发监听器。

      参数

      • listener: () => void

        监听器

      返回 Promise<void>

      await ymx.onAppShow(() => {
      console.log('appShow');
      });
    • 订阅监听一个事件,触发一次后失效。

      参数

      返回 Promise<void>

      await ymx.once({
      eventName: 'my-once',
      listener: (data) => {
      console.log('once data', data);
      }
      });
    • 监听罗盘数据事件

      参数

      返回 Promise<void>

      await ymx.onCompassChange((res) => {
      console.log(`Compass x:${res.x}, y:${res.y}, z:${res.z}`);
      });
    • 当用户确认隐私协议时触发,如果用户已确认隐私协议则立即触发监听器。

      参数

      • listener: (isAgreed: boolean) => void

        isAgreed 是否同意了协议

      返回 Promise<void>

    • 监听陀螺仪数据事件

      参数

      返回 Promise<void>

      await ymx.onGyroscopeChange((res) => {
      console.log(`Gyroscope x:${res.x}, y:${res.y}, z:${res.z}`);
      });
    • 在新窗口中打开链接

      参数

      返回 Promise<void>

      ymx.open({
      url: 'https://xw.qq.com/'
      }).then(() => {
      console.log('成功');
      }).catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
      ymx.open({
      url: 'https://xw.qq.com/',
      style: 'dialog',
      onResult: (result: ESObject) => {
      // 关闭子窗口时返回的结果 ymx.close(result)
      console.log(result);
      }
      }).then(() => {
      console.log('成功');
      }).catch((e: ESObject) => {
      alert(`失败 ${JSON.stringify(e)}`);
      });
    • 打开网络设置

      返回 Promise<void>

      await ymx.openNetworkSettings();
      
    • 删除布局规则

      参数

      • index: number

        从 0 开始的序号

      返回 Promise<void>

    • 从本地缓存中移除指定 key

      参数

      返回 Promise<void>

      await ymx.removeStorage({
      key: 'key1'
      });
    • 网络请求

      参数

      返回 Promise<RequestResult>

      //POST
      await ymx.request({
      url: 'https://www.yimenapp.com/doc/echo2',
      method: 'POST',
      data: {
      key1: 'value 1',
      hello: '世界'
      },
      onNetworkTaskCreated(task) {
      console.log('request task', task);
      },
      onReceiveResponseHeaders: (headers) => {
      console.log('服务器响应头', headers);
      },
      onDataSendProgress: (progress) => {
      console.log(`共需发送 ${progress.totalSize} Bytes,已发送 ${progress.sendSize} Bytes`);
      },
      onDataReceiveProgress: (progress) => {
      console.log(`共需接收 ${progress.totalSize} Bytes,已接收 ${progress.receiveSize} Bytes`);
      }
      });

      //GET
      await ymx.request({
      url: 'https://www.yimenapp.com/doc/echo2',
      method: 'GET'
      });
    • 请求允许通知

      • 如果用户明确拒绝了通知,再次调用请求允许通知时无效,需要去系统设置里面手动允许通知。

      返回 Promise<void>

    • 同步方法,构建插件 js API 接口实例。

      此接口返回 object 类型,为获得接口类型验证和智能提示,请按如下操作:

      • 安装插件的 TypeScript 接口类型定义包,以 ymx-wechat 插件为例
      npm install --save-dev @ymxjs/ymx-wechat
      
      • 将 requirePlugin 返回值强制转换为插件的对应类型 YmxWechat
      const wechat = ymx.requirePlugin('ymx-wechat') as YmxWechat;
      // 至此,调用 wechat 下的接口即可获得开发环境类型验证和智能提示
      // wechat.login...

      参数

      • pluginId: string

        插件 ID

      返回 object

    • 保存图片到系统相册

      返回 Promise<void>

      //本地临时文件路径
      const localFile = 'fs://temp/img.jpg';
      try {
      //下载图片
      await ymx.downloadFile({
      url: 'https://i.yimenyun.net/sys/2.jpg',
      filePath: localFile
      });
      alert('已下载,即将保存到相册。');
      //保存到相册
      await ymx.saveImageToPhotosAlbum({
      filePath: localFile
      });
      alert('已保存到相册');
      } catch (err) {
      alert(err.message);
      } finally {
      //删除临时文件
      const fs = ymx.getFileSystemManager();
      if (await fs.exist({ path: localFile })) {
      await fs.remove({ path: localFile });
      }
      }
    • 保存视频到系统相册

      返回 Promise<void>

      //本地临时文件路径
      const localFile = 'fs://temp/video.mp4';
      try {
      //下载视频
      await ymx.downloadFile({
      url: 'http://cdn.myapp.ltd/sys/sunflower.mp4',
      filePath: localFile
      });
      alert('已下载,即将保存到相册。');
      //保存到相册
      await ymx.saveVideoToPhotosAlbum({
      filePath: localFile
      });
      alert('已保存到相册');
      } catch (err) {
      alert(err.message);
      } finally {
      //删除临时文件
      const fs = ymx.getFileSystemManager();
      if (await fs.exist({ path: localFile })) {
      await fs.remove({ path: localFile });
      }
      }
    • 调起客户端扫码界面进行扫码

      参数

      返回 Promise<CodeResult>

      const res = await ymx.scanCode({
      scanType: ['barCode', 'qrCode']
      });
      alert(JSON.stringify(res));
      ymx.scanCode({
      onlyFromCamera: true
      }).then(res => {
      alert(JSON.stringify(res));
      });
    • 设置是否保持常亮状态

      参数

      返回 Promise<void>

      ymx.setKeepScreenOn({
      keepScreenOn: true
      }).then(() => {
      alert('已开启屏幕常亮');
      });
      ymx.setKeepScreenOn({
      keepScreenOn: false
      }).then(() => {
      alert('已关闭屏幕常亮');
      });
    • 设置当前布局选项

      参数

      返回 Promise<void>

    • 将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。

      参数

      返回 Promise<void>

      await ymx.setStorage({
      key: 'key1',
      data: 'value 1'
      });
      await ymx.setStorage({
      key: 'key2',
      data: {
      name: '张三',
      age: 26
      }
      });
    • 设置主题

      参数

      返回 Promise<void>

    • 显示 loading 提示

      参数

      返回 Promise<void>

      await ymx.showLoading({
      title: '加载中...',
      mask: true
      });
    • 显示模态弹框

      参数

      返回 Promise<ShowModalResult>

      ymx.showModal({
      title: '确认',
      content: '确实退出吗?',
      confirmText: '退出',
      cancelText: '取消'
      }).then(res => {
      alert(JSON.stringify(res));
      });
    • 吐司提示

      参数

      返回 Promise<void>

      await ymx.showToast({
      title: 'hello world',
      duration: 2000
      });
    • 开始监听罗盘数据

      参数

      返回 Promise<void>

      await ymx.startCompass({
      interval: 200
      });
    • 停止监听加速计数据

      返回 Promise<void>

      await ymx.stopAccelerometer();
      
    • 停止监听罗盘数据

      返回 Promise<void>

      await ymx.stopCompass();
      
    • 停止监听陀螺仪数据

      返回 Promise<void>

      await ymx.stopGyroscope();
      
    • 系统分享链接、图片、视频、文件、文字等内容。

      参数

      返回 Promise<void>

      //链接
      await ymx.systemShare({
      title: 'APP 打包',
      description: '信赖之选',
      thumb: 'https://i.cdn.yimenapp.com/sys/logo.png',
      content: {
      link: 'https://www.ymxapp.com'
      }
      });

      //文本
      await ymx.systemShare({
      title: '文本标题',
      content: {
      text: 'hello 世界'
      }
      });

      //图片链接
      await ymx.systemShare({
      title: '图片标题',
      content: {
      imageUrl: 'https://i.yimenyun.net/sys/1.jpg'
      }
      });

      const image = await ymx.downloadFile({
      url: 'https://i.yimenyun.net/sys/1.jpg'
      });
      //本地图片
      await ymx.systemShare({
      title: '图片标题',
      content: {
      imageFilePath: image.tempFilePath
      }
      });

      //视频链接
      await ymx.systemShare({
      title: '视频标题',
      content: {
      videoUrl: 'https://cdn.myapp.ltd/sys/sunflower.mp4'
      }
      });

      const video = await ymx.downloadFile({
      url: 'https://cdn.myapp.ltd/sys/sunflower.mp4'
      });
      //本地视频
      await ymx.systemShare({
      title: '视频标题',
      content: {
      videoFilePath: video.tempFilePath
      }
      });

      //文件链接
      await ymx.systemShare({
      title: '文件标题',
      content: {
      fileUrl: 'https://www.yimenapp.com/doc/doc.pdf'
      }
      });

      const file = await ymx.downloadFile({
      url: 'https://www.yimenapp.com/doc/doc.pdf'
      });
      //本地文件
      await ymx.systemShare({
      title: '文件标题',
      content: {
      filePath: file.tempFilePath
      }
      });
    • 上传文件

      参数

      返回 Promise<UploadFileResult>

      //相册选图 -> 压缩 -> 上传
      try {
      //从相册选图
      const choose = await ymx.chooseMedia({
      sourceType: ['album'],
      mediaType: ['image'],
      count: 1
      });
      const imageFile = choose.tempFiles[0]?.tempFilePath;
      if (imageFile) {
      //可直接上传相册原始图片
      //await ymx.uploadFile({
      // url: 'https://www.yimenapp.com/doc/echo2',
      // filePath: imageFile
      //});
      const compressedImage = 'fs://temp/file-to-upload.jpg';
      //压缩图片
      await ymx.compressImage({
      src: imageFile,
      compressedWidth: 720,
      quality: 85,
      filePath: compressedImage
      });
      //上传图片
      const res = await ymx.uploadFile({
      url: 'https://www.yimenapp.com/doc/echo2',
      filePath: compressedImage,
      onNetworkTaskCreated(task) {
      console.log('upload task', task);
      },
      onDataSendProgress: (progress) => {
      console.log(`总共 ${progress.totalSize} Bytes,已上传 ${progress.sendSize} Bytes`);
      }
      });
      alert(`已上传,服务器返回字符串:\n${res.data}`)
      }
      } catch (err) {
      alert(`失败 ${err.message}`)
      }

      //上传 fs:// 本地文件
      await ymx.uploadFile({
      url: 'https://www.yimenapp.com/doc/echo2',
      filePath: 'fs://file/my_dir/doc.pdf'
      });
    • 使手机发生较长时间的振动(400 ms)

      返回 Promise<void>

      await ymx.vibrateLong();
      
    • 使手机发生较短时间的振动(15 ms)

      参数

      返回 Promise<void>

      await ymx.vibrateShort({
      type: 'medium'
      });
    • 浏览多图

      参数

      返回 Promise<void>

      await ymx.viewImages({
      activeIndex: 1,
      items:[
      {
      url :"http://i.cdn.yimenapp.com/sys/1.jpg",
      text:"美丽的大自然 01"
      },
      {
      url :"http://i.cdn.yimenapp.com/sys/2.jpg",
      text:"美丽的大自然 02"
      },
      {
      url :"http://i.cdn.yimenapp.com/sys/3.jpg"
      },
      {
      url :"http://i.cdn.yimenapp.com/sys/4.jpg"
      },
      {
      url :"http://i.cdn.yimenapp.com/sys/5.jpg"
      }
      ],
      onLongPress: (index) => {
      console.log(`长按了图片 ${index}`)
      }
      })