Search code examples
androidgoogle-apigoogle-drive-apiandroid-contentresolver

Google Drive API v3: get FileID from Android content URI


My Android app needs to share a file of the user's choice from Google Drive and obtain the link. The v3 Google Drive API doesn't provide its own file pickers on Android, so I'm using the system file picker.

The problem is that com.google.api.services.drive.Drive.Permissions#create requires a fileID as the first parameter, whereas what the system file picker gives me is a content: URI. How do I look up the fileID corresponding to this URI? When I try DocumentsContract.getDocumentId(url) or DocumentsContract.getDocumentId(url).split("doc=encoded=")[1] (or one of the ContentResolver ID columns) as the URI-to-ID function, I get a 404. When I try this answer, the regex doesn't match anything.

An example of a content: URI I need to translate is:

content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3DBEskNs6jf7jS24J%2FMnNdnr7fDrih03xNetfcCUsggemjSmpiWBC5

I've tried searching for the name and mimetype obtained from the ContentResolver, but this has 2 issues: it requires files.metadata.readonly permission, and it doesn't help if there's a file of the same name in a different folder of the same user's Drive.


Solution

  • In theory the Javascript based Google Picker API could be run in a webview.

    see https://developers.google.com/drive/api/v3/picker

    UPDATE: I see that others who have tried this approach have experienced problems such as sizing to fit phone screens, etc. so this is not a good approach.

    Google Drive Picker (JavaScript) not mobile friendly / responsive