开发环境:

  1. Dev Eco 4.x 版本
  2. OpenHarmony SDK 4.0.x 版本

记录我在开发过程中常用的一些业务逻辑

一、window 管理

隐藏/显示 —— 状态栏 | 导航栏

官方文档

参考示例:

    // 在 mainAbility 中获取主 window
    windowStage.getMainWindow().then((win: window.Window) => {
      AppStorage.setOrCreate('mainWindow', win);

    }).catch(() => {
      LogUtils.e(TAG, `get device screen info failed.`);
    });


    // 在任意 page 中调用
    /**
    * 设置导航栏,状态栏 显示 与 隐藏
    * @param names
    */
    private setSystemBarVisible(names: Array<'status'|'navigation'>) {
        let win = AppStorage.get('mainWindow') as Window.Window;
        // let names: Array<'status'|'navigation'> = ['navigation', 'status'];
        win.setWindowSystemBarEnable(names, (err: BusinessError) => {
        let errCode: number = err.code;
        if (errCode) {
            LogUtils.e(TAG, 'Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
            return;
        }
        LogUtils.i(TAG, 'Succeeded in setting the system bar to be visible.');
        });
    }

二、锁屏管理

官方文档

判断当前是否为锁屏状态

import screenLock from '@ohos.screenLock';

// ...
let isLocked = screenLock.isLocked();

三、系统电源查询状态

官方文档

查看是否熄屏

检测当前设备是否处于活动状态。有屏的设备为亮屏状态,无屏的设备为非休眠状态。

import power from '@ohos.power';

 let isActive = power.isActive();

四、应用跳转

跳转 setting

      const context = getContext(this) as common.UIAbilityContext;

      let want: Want = {
        deviceId: "",
        bundleName: 'com.ohos.settings', // com.ohos.settings
        abilityName: 'com.ohos.settings.MainAbility', // com.ohos.settings
      };

      // previewer 无法调用
      context.startAbility(want).then((res) => {
        console.log(res + "cdwDebug");
      })

如果需要跳转系统设置的 二级页面,三级页面,需要在 settings 中配置冷启动热启动 相关的参数,

参考案例:
https://gitee.com/openharmony/applications_settings/pulls/702

五、通知管理快速开发

使用当前应用发布一个通知的步骤

  1. 请求通知权限
  2. 获取当前应用的 boundleName 和 abilityName
  3. 获取 wantAgent 实例
  4. 发布通知

API 9 写法,但是后面的写法基本类似

// 发布通知前在合适的时机调用 (notificationUtils)
openNotificationPermission()

// 获取当前应用的信息
let bundleName = this.context.abilityInfo.bundleName;
let abilityName = this.context.abilityInfo.name;

    // 3. 获取 wantAgent 实例
createWantAgent(bundleName, abilityName).then(want => {
  this.wantAgentObj = want;
}).catch((err: Error) => {
  console.error(`getWantAgent fail, err: ${JSON.stringify(err)}`);
});


// 4. 发布通知
publishNotification(xxx)

export function openNotificationPermission() {
  notification.requestEnableNotification().then(() => {
    console.info('Enable notification success');
  }).catch((err) => {
    console.error('Enable notification failed because ' + JSON.stringify(err));
  });
}

// notificationUtils.ts
export function createWantAgent(bundleName: string, abilityName: string): Promise<WantAgent> {
  let wantAgentInfo = {
    wants: [
      {
        bundleName: bundleName,
        abilityName: abilityName
      }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
  } as wantAgent.WantAgentInfo;
  return wantAgent.getWantAgent(wantAgentInfo);
}

export function publishNotification(title: string, text: string, wantAgentObj: WantAgent) {
  let notificationRequest: notification.NotificationRequest = {
    id: 1000,
    slotType: notification.SlotType.SOCIAL_COMMUNICATION,
    content: {
      contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: title,
        text: text
      }
    },
    wantAgent: wantAgentObj,
    actionButtons: [
      {
        title: "粘贴",
        wantAgent: wantAgentObj
      }
    ]
  };
  notification.publish(notificationRequest).catch((err: Error) => {
    console.error(`[ANS] publish failed,message is ${err}`);
  });
}

主要还是看文档为主,收集了一些常用的工具及方法

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐