android - 附近连接 API : Cannot access received file on Android 10

标签 android google-nearby google-nearby-connections

我关注 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_URIMediaStore.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/

相关文章:

ios - 使用ios swift取消订阅附近的api后如何禁用蓝牙?

android - 为什么使用 Android 附近共享时通过蓝牙传输文件?

java - 无法启动 Activity ComponentInfo{com.example.countryselect/com.example.countryselect.OfferSelect}

android - 如何显示/隐藏 ListFragment 中的 Activity View

文件后面的 Android 布局引用 xml 元素

android - 使用 Google Nearby Connections 2.0 时是否可以监控发现过程?

android自定义通知不适用于约束布局

android - Google Nearby 通知 API 不显示新通知

java - 如何访问已使用 Android 11 的附近连接 API 传输的文件,因为文件存储在附近的范围存储中?

android - 附近连接最大连接设备 - 说明