HarmonyOS ohos.permission.READ_PASTEBOARD申请后为什么拿不到剪切板

已经申请好了ohos.permission.READ_PASTEBOARD权限。但是

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

一直返回的是个undefined。

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

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

//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)
分享
微博
QQ
微信
回复
2天前
相关问题
复制图片到剪切板并获取剪切板消息
782浏览 • 1回复 待解决
HarmonyOS 如何使用剪切板功能
71浏览 • 1回复 待解决
系统剪切板功能的使用
1139浏览 • 1回复 待解决
HarmonyOS 如何获取剪切板的内容
413浏览 • 1回复 待解决
HarmonyOS 获取当前剪切板数据值
33浏览 • 1回复 待解决
HarmonyOS PAD上从剪切板获取数据失败
58浏览 • 1回复 待解决
HarmonyOS 怎么把内容复制到剪切板
529浏览 • 1回复 待解决
是否支持在应用后台获取剪切板数据
461浏览 • 1回复 待解决
JS FA调用 java PA,取到参数剪切板问题
5216浏览 • 1回复 待解决