我关注 this guide目标是传输图像文件,接收方应通过 REST API 上传该图像文件。
Android 10 阻止访问公共(public)文件夹,例如“下载”文件夹,所有从 Nearby Connections API 接收到的文件都存储在“附近”文件夹中。File payloadFile = filePayload.asFile().asJavaFile();
我有一个 Payload
对象,并且正如指南建议的那样,上面的代码应该获取文件。不幸的是,上面的代码在以 api 29 为目标并在 Android 10 设备上运行时返回 null。在早期的 Android 版本上运行良好。
我可以通过 File payloadFile = filePayload.asFile().asParcelFileDescriptor();
获得 ParcelFileDescriptor但不确定如何访问该文件?
通过 ParcelFileDescriptor
我尝试通过以下方式读取文件,但我总是获得某种许可或错误的访问异常:BitmapFactory.decodeStream(FileInputStream(payloadFileDescriptor.fileDescriptor))
或者BitmapFactory.decodeFileDescriptor(payloadFileDescriptor.fileDescriptor)
我可以看到该文件正确存储在“下载”文件夹中,并通过文件浏览器应用程序打开它。
还尝试通过内容解析器( MediaStore.Downloads.EXTERNAL_CONTENT_URI
和 MediaStore.Images.EXTERNAL_CONTENT_URI
)访问,但没有运气。
这里需要注意的是文件保存时没有扩展名,所以也许这就是 Mediastore 找不到任何东西的原因?
我使用“com.google.android.gms:play-services-nearby:17.0.0”。
如前所述,我真的很想收到一个文件并上传它。这对于 Android 10 上的 Nearby Connections API 是完全不可能的吗?
最佳答案
附近连接 18.0.0 已发布。你现在可以这样做 -
if (VERSION.SDK_INT >= VERSION_CODES.Q) {
// Because of https://developer.android.com/preview/privacy/scoped-storage, we are not
// allowed to access filepaths from another process directly. Instead, we must open the
// uri using our ContentResolver.
Uri uri = filePayload.asFile().asUri();
try {
// Copy the file to a new location.
InputStream in = context.getContentResolver().openInputStream(uri);
copyStream(in, new FileOutputStream(new File(context.getCacheDir(), filename)));
} catch (IOException e) {
// Log the error.
} finally {
// Delete the original file.
context.getContentResolver().delete(uri, null, null);
}
关于android - 附近连接 API : Cannot access received file on Android 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59985347/