HarmonyOS ohos.permission.READ\_PASTEBOARD申请后为什么拿不到剪切板?

已经申请好了ohos.permission.READ\_PASTEBOARD权限。但是

let systemPasteboard = pasteboard.getSystemPasteboard() 
let result: pasteboard.PasteData = systemPasteboard.getDataSync() 

一直返回的是个undefined。

阅读 466
1 个回答

现在获取剪贴板内容都需要用户申请权限。下面这个例子第一次询问获得权限后,下次就不用再申请了:

//down下载
export function down(fileUrl: string, context: common.UIAbilityContext){
  const fileSuffixName = fileUrl.split('.')[fileUrl.split('.').length - 1]
  const fileFullName = fileUrl.split('/')[fileUrl.split('/').length - 1]
  console.log('context.filesDir', context.filesDir)
  const filePath = `${context.filesDir}/${new Date().getTime() + '.' + fileSuffixName}`;
  console.error(filePath);
  try {
    request.downloadFile(context, { url: fileUrl,filePath: filePath }, (err, data) => {
      if (err) {
        console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
        return;
      }
      // 监听文件下载的实时情况 receivedSize已下载 totalSize总大小
      data.on('progress', (receivedSize, totalSize) => {
        console.info("upload totalSize:" + totalSize + "  receivedSize:" + receivedSize);
      })
      // 监听文件下载完成
      data.on('complete', () => {
        console.info('Download task completed.');
      })
    });
  } catch (err) {
    console.error('err.code : ' + err.code + ', err.message : ' + err.message);
  }
}

//down调用
down('xxxx')
import hilog from '@ohos.hilog';
import { BusinessError } from '@ohos.base';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
import bundleManager from '@ohos.bundle.bundleManager';
import pasteboard from '@ohos.pasteboard';
async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
  let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
  // 获取应用程序的accessTokenID
  let tokenId: number = 0;
  try {
    let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
    tokenId = appInfo.accessTokenId;
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
  }
  // 校验应用是否被授予权限
  try {
    grantStatus = await atManager.checkAccessToken(tokenId, permission);
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`);
  }
  return grantStatus;
}
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State msgList: Array<string> = [];
  @State permission_state: boolean = true;
  reqPermissionsFromUser(permissions: Array<Permissions>): void {
    let context = getContext(this) as common.UIAbilityContext;
    let atManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(context, permissions).then((data) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] === 0) {
          // 用户授权,可以继续访问目标操作
          this.permission_state = true;
          this.msgList.push('申请权限成功');
        }
        else {
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
          console.error("user did not grant!")
          this.permission_state = false;
          this.msgList.push('申请权限失败');
        }
      }
    }).catch((err: String) => {
    })
  }
  async getPaste() {
    const permissions: Array<Permissions> = ['ohos.permission.READ_PASTEBOARD'];
    let grantStatus1: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[0]);
    if (grantStatus1 === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      try {
        let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
        systemPasteboard.getData((err: BusinessError, pasteData: pasteboard.PasteData) => {
          if (err) {
            console.error('Failed to get PasteData. Cause: ' + err.message);
            return;
          }
          let text: string = pasteData.getPrimaryText();
          this.msgList.push('剪贴板内容:'+text);
        });
      } catch (err) {
        hilog.error(0x0000, 'testTag', '%{public}s', `get oaid by promise catch error: ${err.code} ${err.message}`);
      }
    } else {
      // 申请权限
      if(this.permission_state) {
        this.reqPermissionsFromUser(permissions)
      }else{
      }
    }
  }
  build() {
    Column() {
      Button({ type: ButtonType.Normal, stateEffect: true }) {
        Text('读取剪贴板内容')
          .fontColor(Color.White)
          .fontSize(20)
      }
      .borderRadius(8)
      .width('45%')
      .height('5%')
      .backgroundColor(0x317aff)
      .onClick(() => {
        this.getPaste()
        try {
          let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
          systemPasteboard.getData((err: BusinessError, pasteData: pasteboard.PasteData) => {
            if (err) {
              console.error('Failed to get PasteData. Cause: ' + err.message);
              return;
            }
            let text: string = pasteData.getPrimaryText();
            this.msgList.push('剪贴板内容:'+text);
          });
        } catch (err) {
          hilog.error(0x0000, 'testTag', '%{public}s', `get oaid by promise catch error: ${err.code} ${err.message}`);
        }
      })
      ForEach(this.msgList, (item: string) => {
        Text(item)
          .fontSize(25)
          .textOverflow({ overflow: TextOverflow.Clip })
          .maxLines(10)
          .width('80%')
          .margin({ top: 5 })
      })
    }
    .width('100%')
    .height('100%')
  }
}N1.mp4',this.context)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏