鴻蒙開發實戰案例:圖片分享案例

介紹

本示例介紹使用Share Kit和ShareExtensionAbility實現從圖庫分享圖片到應用的場景。該場景多用于聊天類應用。

效果圖預覽

使用說明

  1. 打開圖庫選擇一張圖片,點擊左下角分享按鈕拉起分享彈窗。
  2. 在分享彈窗中選擇需要分享的應用,將圖片分享到應用。

實現思路

  1. 通過Share Kit(分享服務)構造分享數據,啟動分享面板選擇需要分享過去的應用啟動分享。
  // 構造ShareData,需配置一條有效數據信息
  const contextFaker: Context = getContext(this);
  let filePath = contextFaker.filesDir + '/exampleImage.jpg'; // 僅為示例 請替換正確的文件路徑
  // 獲取精準的utd類型
  let utdTypeId = utd.getUniformDataTypeByFilenameExtension('.jpg', utd.UniformDataType.IMAGE);
  let shareData: systemShare.SharedData = new systemShare.SharedData({
    utd: utdTypeId,
    uri: fileUri.getUriFromPath(filePath),
    title: '圖片標題', // 不傳title字段時,顯示圖片文件名
    description: '圖片描述', // 不傳description字段時,顯示圖片大小
    thumbnail: new Uint8Array() // 優先使用傳遞的縮略圖預覽  不傳則默認使用原圖做預覽圖
  });
  shareData.addRecord({
  utd: utdTypeId,
  uri: fileUri.getUriFromPath(filePath),
  title: '圖片標題', // 不傳title字段時,顯示圖片文件名
  description: '圖片描述', // 不傳description字段時,顯示圖片大小
  });
  // 進行分享面板顯示
  let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
  let context = getContext(this) as common.UIAbilityContext;
  controller.show(context, {
    selectionMode: systemShare.SelectionMode.SINGLE,
    previewMode: systemShare.SharePreviewMode.DETAIL,
  }).then(() => {
    console.info('ShareController show success.');
  }).catch((error: BusinessError) => {
    console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
  });
  1. 構建分享能力Ability,需要在應用配置文件(src/main/module.json5)的skills配置中注冊。配置actions為ohos.want.action.sendData,并且uris需窮舉所有支持的數據類型。
 "skills": [
   {
      "entities": [
      "entity.system.home"
      ],
     "actions": [
       "action.system.home",
       "ohos.want.action.sendData"
     ],
     "uris": [
       {
         "scheme": "file",
         "utd": "general.image",
         "maxFileSupported": 1
       }
      ]
    }
 ]
  1. 在Ability被系統啟動時,Ability會收到want數據,在onCreate中want數據中無直接的圖片地址通過systemShare.getSharedData獲取的圖片地址,在onNewWant中want數據中有直接的圖片數據可以直接使用。
  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    if (want.parameters!['ability.params.stream'] !== undefined) {
      AppStorage.setOrCreate('imageUri', want.parameters!["ability.params.stream"].toString());
    }
  }

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    systemShare.getSharedData(want)
      .then((data: systemShare.SharedData) => {
        data.getRecords().forEach((record: systemShare.SharedRecord) => {
          // 處理分享數據
          AppStorage.setOrCreate('imageUri', record.uri)
        });
      })
  }
  1. 通過systemShare.getSharedData或want數據中獲取分享的圖片地址,直接在頁面中渲染頁面。
  aboutToAppear() {
    if (AppStorage.get('imageUri') !== undefined) {
      this.shareImageUri = AppStorage.get('imageUri');
      this.textDetailData.push({
        profilePicture: $r('app.media.photo0'),
        shareImageUri: this.shareImageUri,
        content: ''
      });
      // 通知lazyForeach重新加載數據
      this.dataSource.modifyAllData(this.textDetailData);
    }
  }

高性能知識點

不涉及

工程結構&模塊類型

   shareimagepage                             // har類型
   |---components
   |   |---ShareImagePage.ets                 // 視圖層-分享頁面 
   |   |---ListDataSource.ets                 // 數據模型層-聊天列表數據 

寫在最后

  • 如果你覺得這篇內容對你還蠻有幫助,我想邀請你幫我三個小忙:
  • 點贊,轉發,有你們的 『點贊和評論』,才是我創造的動力。
  • 關注小編,同時可以期待后續文章ing??,不定期分享原創知識。
  • 想要獲取更多完整鴻蒙最新學習知識點,請移步前往小編:https://gitee.com/MNxiaona/733GH/blob/master/jianshu
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容