如何访问使用 Nearby Connections API 与 android 11 传输的文件,因为文件存储在 Nearby 的范围存储中?

问题描述

我正在尝试使用 googles Nearby Connections API 传输文件。在很大程度上,我可以让传输的所有组件正常工作,以便传输所有文件数据,但问题是文件数据随后存储在 Nearby 的范围存储中,因此我无法从我的应用程序访问它以进行处理将该数据转换为适当的文件类型,然后根据需要进行保存和重命名

我用来尝试处理负载的当前方法

private void processFilePayload(long payloadId) {

// BYTES and FILE Could be received in any order,so we call when either the BYTES or the FILE
// payload is completely received. The file payload is considered complete only when both have
// been received.
    Payload filePayload = completedFilePayloads.get(payloadId);
    String filename = filePayloadFilenames.get(payloadId);

    if (filePayload != null && filename != null) {
        completedFilePayloads.remove(payloadId);
        filePayloadFilenames.remove(payloadId);

// Get the received file (which will be in the Downloads folder)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

              File fromPayload = filePayload.asFile().asJavaFile();
              Uri uri = Uri.fromFile(fromPayload);

              try {
              // copy the file to a new location.
                   InputStream in = getApplicationContext().getContentResolver().openInputStream(uri);
                   copyStream(in,new FileOutputStream(new File(getApplicationContext().getCacheDir(),filename)));
                  } catch (IOException e) {
                      // Log the error.
                      Log.e("copy file",e.toString());
                  } finally {
                      // Delete the original file.
                      getApplicationContext().getContentResolver().delete(uri,null,null);
                  }

            } else  {
            File payloadFile = filePayload.asFile().asJavaFile();

            // Rename the file.
            payloadFile.renameto(new File(payloadFile.getParentFile(),filename));
            }
        }
    }

});

由于 android 11 的范围存储能够访问文件,需要使用文件 Uri 来创建具有内容解析器的输入流以访问文件

根据 Nearby 文档,应该有一个 Payload.File.asUri 方法,因此我可以使用 Uri payloadUri = filePayload.asFile().asUri(); 行,但尽管使用了 Nearby 的最新版本,但实际上这在 API 中并不可用。

除此之外,根据 google Nearby 文档,Payload.File.AsJavaFile() 的使用应该被弃用

我已经看到了一些其他类似问题的答案,其中建议使用 Media.Store,但这是不可能的,因为该文件还没有任何扩展名,因此不会显示为任何特定文件类型。

注意:我已在清单和运行时请求读/写外部存储权限。

解决方法

===更新===

Payload.asFile.asUri() 在 com.google.android.gms:play-services-nearby:18.0.0 中可用

============

抱歉。我们将很快发布更新并正确公开 #asUri。

与此同时,如果您的目标是 API 29,您可以使用 requestLegacyExternalStorage=true 作为解决方法。 (查看更多:https://developer.android.com/about/versions/11/privacy/storage