我的应用无法在 google 驱动器的 "appDataFolder" 中创建文件

My app can not create file in "appDataFolder" of google drive

如何在 google 驱动器“appDataFolder”中创建文件?

我创建了 google 开发者控制台设置,这是创建文件和访问“appDataFolder”所必需的。

google developer console

Android Studio 输出错误信息如下。

W/System.err: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
    {
      "code": 403,
      "errors": [
        {
          "domain": "global",
          "message": "The granted scopes do not allow use of the Application Data folder.",
          "reason": "insufficientScopes"
        }
      ],
      "message": "The granted scopes do not allow use of the Application Data folder."
    }
W/System.err:     at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at com.example.test1.MainActivity.run(MainActivity.java:131)
        at java.lang.Thread.run(Thread.java:923)

源代码是

                        File body = new File();
                        body.setName(FILE_TITLE);//fileContent.getName());
                        body.setMimeType("text/plain");
                        body.setParents(Collections.singletonList("appDataFolder"));

                        File file = service.files().create(body, content)
                                .setFields("id")
                                .execute();

如果在源代码中注释掉以下行,我的应用程序可以在 google 驱动器中创建一个文件 顶级文件夹不是“appDataFolder”。

body.setParents(Collections.singletonList("appDataFolder"));

Android Studio 4.1.2 enter image description here

此致。 提前致谢。

虽然从您的开发人员控制台图像的外观来看,您似乎包含大量范围。这里的问题不在于您在 google 开发者控制台中的设置,而在于您授权给用户的范围。

当您 运行 您的应用程序要求用户同意您访问他们的某些数据时,这就是您的应用程序的授权范围。它定义了用户授予您的应用程序访问权限的内容。

如果您的代码只请求只读访问,然后您尝试写入它,那么您将看到 insufficientScopes 错误消息。

您需要检查您正在使用的方法需要什么范围,然后确保在授权用户时您正在请求该范围。

我猜你有这样的东西

private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_METADATA_READONLY);

您需要包含此范围 https://www.googleapis.com/auth/drive.appdata,这可能类似于 DriveScopes.DRIVE_APPDATA

请记住,一旦在您的应用程序中更改了范围,您将需要重新授权用户。如果您存储同意,则需要将其删除才能再次请求授权。