【发布时间】:2021-03-17 09:26:19
【问题描述】:
我正在尝试使用 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,但这是不可能的,因为该文件还没有任何扩展名,因此不会显示为任何特定的文件类型。
注意:我已在清单和运行时请求读/写外部存储权限。
【问题讨论】:
-
请举一些文件名的例子。如果它们位于公共下载文件夹中(请参阅代码中的注释),那么您为什么建议它们位于 Android 目录中的私有文件夹中。进一步:如果它们确实位于 Android/data 目录中的私有文件夹中,那么它们对于 mediastore 来说是遥不可及的。请找出您的文件在哪里。
-
文件存储在文件路径 /storage/emulated/0/Download/Nearby/ 下的 Nearby 下载下,然后文件名是有效负载 ID,因此类似于 -6159828823084046368
-
Because of android 11's scoped storage to be able to access the file the files Uri needs to be used to create an input stream with a content resolver to access the file.All 与作用域存储无关。您的应用程序可以尝试使用new File( "/storage/emulated/0/Download/Nearby").list();列出附近文件夹中的 als 文件您是否已经尝试过?如果可以的话,您可以使用新的 FileInputStream 来读取文件。 Files 应用程序是否显示来自 ./Download/Nearby 的这些文件?您还可以在 MediaStore 中查询 RELATIVE_PATH 下载/附近。 -
Nearby 文件夹将在未来 2 周内推出的更新中重命名为“.nearby”。手动查找是一种解决方法,直到可以更新 SDK。
标签: java android google-nearby google-nearby-connections