DEV Community

Cover image for Clipboard, Asynchrony, User Permissions, Lock Screen Events, Dialogs
kouwei qing
kouwei qing

Posted on

Clipboard, Asynchrony, User Permissions, Lock Screen Events, Dialogs

[Daily HarmonyOS Next Knowledge] Clipboard, Asynchrony, User Permissions, Lock Screen Events, Dialogs

1. How to share clipboard capabilities with cross-platform containers like H5 and Flutter when HarmonyOS clipboard permissions cannot be applied for?

When clipboard permissions cannot be applied for, how to share clipboard capabilities with cross-platform containers such as H5 and Flutter?

The order ID can be passed from the H5 page to ArkTS, which then copies it to the clipboard. For data interaction between the two, refer to the documentation: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/web-in-page-app-function-invoking-V5

ArkTS copy-paste function reference demo:

import { pasteboard } from '@kit.BasicServicesKit';
@State message: string = 'Hello World'
Text(this.message).onClick(() => {
  const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, this.message)
  const systemPasteboard = pasteboard.getSystemPasteboard()
  systemPasteboard.setData(pasteboardData) // Put data into the clipboard
  systemPasteboard.getData().then((data) => {
    if (data) {
      promptAction.showToast({ message: "复制成功" })
    } else {
      promptAction.showToast({ message: "复制失败" })
    }
  })
})
Enter fullscreen mode Exit fullscreen mode

2. What is the meaning of using async/await in HarmonyOS?

When using async/await, does the entire asynchronous call run on the main thread? Does thread switching occur during this process?

Using async/await still operates on the main thread, and no thread switching occurs. Currently, child threads can only be created via taskpool and worker.

3. After the user clicks "Allow" in requestPermissionsFromUser, why does permissionGrantStates in the BundleInfo returned by getBundleInfoForSelf still show -1?

Refer to the following code:

async reqPermissionsFromUser(): Promise<number[]> {
  let context = getContext() as common.UIAbilityContext;
  let atManager = abilityAccessCtrl.createAtManager();
  let grantStatus = await atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']);
  return grantStatus.authResults;
}
// Apply for camera permission
async requestCameraPermission() {
  let grantStatus = await this.reqPermissionsFromUser()
  for (let i = 0; i < grantStatus.length; i++) {
    if (grantStatus[i] === 0) {
      // User authorized, can proceed with the target operation
      this.userGrant = true;
    }
  }
}

async onPageShow() {
  await this.requestCameraPermission();
}
Enter fullscreen mode Exit fullscreen mode

4. How to obtain lock screen events in HarmonyOS?

During video playback, it is necessary to monitor lock screen events and pause playback after locking. Currently, lock screen events cannot be obtained.

Reference demo:

import Base from '@ohos.base';
import CommonEventManager from '@ohos.commonEventManager';

let subscriber: CommonEventManager.CommonEventSubscriber; // Used to save the successfully created subscriber object for subsequent subscription and unsubscription actions

// Subscriber information
let subscribeInfo: CommonEventManager.CommonEventSubscribeInfo = {
  events: [CommonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED, CommonEventManager.Support.COMMON_EVENT_SCREEN_UNLOCKED]
};

// Public event publication callback
function subscribeCB(err: Base.BusinessError, data: CommonEventManager.CommonEventData) {
  if (err) {
    console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
  } else {
    if (data.event == CommonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED) {
      console.info("MWB ", `lock screen`);
    } else if (data.event == CommonEventManager.Support.COMMON_EVENT_SCREEN_UNLOCKED) {
      console.info("MWB ", `unlock screen`);
    }
  }
}


// Subscriber creation callback
function createCB(err: Base.BusinessError, commonEventSubscriber: CommonEventManager.CommonEventSubscriber) {
  if (!err) {
    console.info("createSubscriber");
    subscriber = commonEventSubscriber;
    try {
      CommonEventManager.subscribe(subscriber, subscribeCB);
    } catch (error) {
      let err: Base.BusinessError = error as Base.BusinessError;
      console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
    }
  } else {
    console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
  }
}

// Create a subscriber
try {
  CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (error) {
  let err: Base.BusinessError = error as Base.BusinessError;
  console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}

@Entry
@Component
struct ScreenLockEventManageDemo {

  build() {
    Column() {
      Text('HELLO WORLD')
        .fontSize('20')
    }
    .width('100%')
    .height('100%')

  }
}
Enter fullscreen mode Exit fullscreen mode

5. How to bind an AlertDialog to a page so that all AlertDialogs are closed when the page is closed in HarmonyOS?

AlertDialog can only be set to auto-cancel on click or cancel when a defined button is clicked. To cancel via method calls, try using a custom pop-up CustomDialog.

AlertDialog reference documentation: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-methods-alert-dialog-box-V5

CustomDialog reference documentation: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-methods-custom-dialog-box-V5

Top comments (0)