Google云端硬盘导入Google文档

时间:2015-10-06 16:59:03

标签: android google-drive-api

我有以下代码来获取Google云端硬盘中文件的DriveContents。我能够导入并获取DriveContents MS Word,文本文件等,但是当该文件是Google原生文件(Google Doc,Google表格等)时,我无法获得内容。我的代码如下:

selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
    public void onResult(DriveApi.DriveContentsResult result) {
        try {
            if (!result.getStatus().isSuccess()) {
                // display an error saying file can't be opened
                Log.e(TAG, "Could not get file contents");
                return;
            }

            // DriveContents object contains pointers
            // to the actual byte stream
            DriveContents contents = result.getDriveContents();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            String contentsAsString = builder.toString();

            contents.discard(getGoogleApiClient());

            Log.i(TAG, contentsAsString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

每当我收到Google格式文件时,它只会返回一个不成功的结果,并在我的日志中显示错误。如何获取这些文件的文件内容?我应该做些什么特别的事吗?

我正在阅读以下文档:

https://developers.google.com/drive/android/files

1 个答案:

答案 0 :(得分:2)

不确定这是否是最佳解决方案,但我是通过以下方式完成的。我检查元数据是否为Google格式(文档,表格等),如果是,我有AsyncTask执行以下操作:

// accountName is the email address the user used when choosing which account
String scope = "oauth2:https://www.googleapis.com/auth/drive.file";
token = GoogleAuthUtil.getTokenWithNotification(fragment.getActivity(), accountName, scope, null);

完成上述操作后,您可以使用API​​获取文件:

https://developers.google.com/drive/web/manage-downloads

上面的token会在下载时提供Authentication标头令牌。我们可以将文件导出为docx,pdf等,并以这种方式下载。