当前位置: 首页 > 知识库问答 >
问题:

Android将文件打开并保存到Google Drive SDK

章阳波
2023-03-14

我已经花了六个小时从谷歌的文件,我仍然不知道如何开始与这个。我想做的就是让我现有的Android应用程序可以从Google Drive读取文件,上传新文件到Google Drive,并编辑Google Drive上的现有文件。

我读到过Drive SDK v2专注于让Android(以及一般的移动)开发人员轻松地使用它,但在他们的文档中似乎几乎没有任何关于它的内容。

理想的情况下,我希望有人能指出一些像样的文档、示例或教程来说明如何做到这一点(请记住,我使用的是Android。他们有很多关于如何在Google App Engine中使用Drive的内容;我已经看过了,但我不知道如何从这些内容转换到Android应用程序。)

我需要知道我需要下载哪些库并将其添加到我的项目中,我需要将哪些库添加到我的清单中,以及我如何最终从Google Drive获得一个文件列表,下载一个,然后上传一个修改过的版本。

理想情况下,我希望它能自动处理帐户,就像官方的Google Drive应用那样。

共有1个答案

爱博达
2023-03-14

编辑:Claudio Cherubino说Google Play服务现在是可用的,它将使这个过程变得更容易。然而,没有可用的示例代码(然而,他说它很快就会出现……他们在4个月前就说Google Play服务“很快就会出现”,所以很有可能这个答案将继续成为从Android应用程序访问Google Drive到2013年的唯一有效示例。)

编辑2X:看起来我离开了大约一个月,当我说谷歌不会有一个工作的例子,直到明年。来自谷歌的官方指南在这里:

    null
    null
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
    "oauth2:" + DriveScopes.DRIVE,
    new Bundle(),
    true,
    new OnTokenAcquired(),
    null);
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        try {
            final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory = new JacksonFactory();
            Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
            b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
                @Override
                public void initialize(JSonHttpRequest request) throws IOException {
                    DriveRequest driveRequest = (DriveRequest) request;
                    driveRequest.setPrettyPrint(true);
                    driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
                    driveRequest.setOauthToken(token);
                }
            });

            final Drive drive = b.build();

            final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
            body.setTitle("My Test File");
    body.setDescription("A Test File");
    body.setMimeType("text/plain");

            final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.)
            new Thread(new Runnable() {
                public void run() {
                    try {
                        com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
                        alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
                    } catch (IOException e) {
                        if (!alreadyTriedAgain) {
                            alreadyTriedAgain = true;
                            AccountManager am = AccountManager.get(activity);
                            am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
                            am.getAuthToken (same as before...)
                        } else {
                            // Give up. Crash or log an error or whatever you want.
                        }
                    }
                }
            }).start();
            Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
            if (launch != null) {
                startActivityForResult(launch, 3025);
                return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
            }
        } catch (OperationCanceledException e) {
            // Handle it...
        } catch (AuthenticatorException e) {
            // Handle it...
        } catch (IOException e) {
            // Handle it...
        }
    }
}
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
    if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
        if (jFolder == null) {
            jFolder = Environment.getExternalStorageDirectory();
            jFolder.mkdirs();
        }
        try {

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(gFile.getDownloadUrl());
            get.setHeader("Authorization", "Bearer " + token);
            HttpResponse response = client.execute(get);

            InputStream inputStream = response.getEntity().getContent();
            jFolder.mkdirs();
            java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
            FileOutputStream fileStream = new FileOutputStream(jFile);
            byte buffer[] = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0) {
                fileStream.write(buffer, 0, length);
            }
            fileStream.close();
            inputStream.close();
            return jFile;
        } catch (IOException e) {        
            // Handle IOExceptions here...
            return null;
        }
    } else {
        // Handle the case where the file on Google Drive has no length here.
        return null;
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 3025) {
        switch (resultCode) {
            case RESULT_OK:
                AccountManager am = AccountManager.get(activity);
                am.getAuthToken(Same as the other two times... it should work this time though, because now the user is actually logged in.)
                break;
            case RESULT_CANCELED:
                // This probably means the user refused to log in. Explain to them why they need to log in.
                break;
            default:
                // This isn't expected... maybe just log whatever code was returned.
                break;
        }
    } else {
        // Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like.
    }
}
    null

下面是一些简单的示例代码,演示如何进行更新,包括更新文件时间:

public void updateGFileFromJFile(Drive drive, File gFile, java.io.File jFile) throws IOException {
    FileContent gContent = new FileContent("text/csv", jFile);
    gFile.setModifiedDate(new DateTime(false, jFile.lastModified(), 0));
    gFile = drive.files().update(gFile.getId(), gFile, gContent).setSetModifiedDate(true).execute();
}

清单

您需要以下权限:GET_ACCOUNTS、USE_CREDENTIALS、MANAGE_ACCOUNTS、INTERNET,而且您很有可能还需要WRITE_EXTERNAL_STORAGE,这取决于您希望存储文件的本地副本的位置。

右键单击您的项目,进入它的属性,在Android下将构建目标更改为Google API(如果必须的话)。如果没有,从android下载管理器下载

如果您在一个模拟器上进行测试,请确保它的目标是谷歌API,而不是通用的Android。

您需要在测试设备上设置一个Google帐户。编写的代码将自动使用它找到的第一个Google帐户(这就是[0]的意思)如果你需要下载Google Drive应用程序,那么就可以使用IDK。我当时使用的是API Level15,我不知道这段代码还能工作多久。

以上应该让你开始,希望你能找到你的出路从那里...老实说,这是我到目前为止得到的最多的东西。我希望这能帮助很多人,并为他们节省很多时间。我可以肯定的是,我刚刚写了一个最全面的设置指南,来设置一个Android应用程序来使用Google Drive。可耻的是,谷歌在至少6个不同的页面上传播必要的材料,而这些页面之间根本没有链接。

 类似资料:
  • 问题内容: 用相机拍照后,我想将其保存在该布局中。我还想将其保存到文件中,并在创建活动时能够加载该图片(因此,如果我切换到其他活动并返回到此活动)。到目前为止,我可以拍照并显示它,但是如果我多次切换活动,图片就会丢失。我有以下相关代码: 我使用以下命令加载图片OnCreate : 问题答案: 听起来您的代码可以正常工作,但是当活动恢复时,您将丢失图像。您可能需要用onPostResume()而不是

  • 目前,我的(使用的是Stackoverflow,我自己没有完整地编写)代码如下所示: 我得到错误:“打开失败;EACCES(权限被拒绝)”。 我的舱单是这样的:

  • 我尝试用以下代码保存从internet下载的文件 但在运行时,我得到的错误如下 03-04 20:42:51.080 8972-8972/com.example.me.demo2 E/BitmapFactory:无法解码流:java.io.FileNotFoundExcoop: /storage/emulated/0/.tanks/4a100abb-0e55-4062-8c37-f11f4189e

  • 问题内容: 我已经实现了RPCService,RPCServiceAsync和RPCServieImpl。单击按钮后,将调用服务器端的服务,该服务将从数据库中获取数据并创建文件。创建文件后,我需要在客户端打开该文件,并需要提示一个带有打开/保存选项的对话框。我如何实现此打开文件部分。请提出一种实施t ..的方法。 @Hambend:我还有一个澄清点!..如何在另一个servlet中调用此doGet

  • 问题内容: 是否可以将JSON数据保存到本地文本文件中?因此,稍后我可以通过加载该文件再次使用它,并取回存储的JSON数据。其实我真正想做的是在文本文件中导出JSON数据,以便以后可以用作import.Any的建议或解决方案? 这是我要用于导出到文本的一些示例。 http://jsfiddle.net/k56eezxp/ 问题答案: 是否可以将JSON数据保存到本地文本文件中? 是。当前,链接的j

  • 我的应用程序将一些文件保存到设备上的数据/数据文件夹中。保存远程文件后,我会处理这些文件,并将它们复制到其他文件夹中。在之前测试过的所有设备上,All都能正常工作,但在galaxy s3上会生成空指针异常。似乎我不被允许在那个文件夹上写或处理文件!但只有新的星系s3!我也无法使用EclipseDDMS文件浏览器在数据文件夹中找到任何文件,而在模拟器(相同的android版本)中,我可以正确查看所有