如何在android中将文件上传到Google云端硬盘

时间:2015-04-01 05:35:11

标签: android google-drive-api google-drive-android-api

我从这段代码中引用

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...
        }
    }
}

在jsonHttpRequestInitializer中我遇到了问题。 [无法解析GoogleClient $ Builder。它是从所需的.class文件间接引用的]请告诉我我必须做的事情......

1 个答案:

答案 0 :(得分:2)

您可以在Android上使用两种不同的API:RESTGDAA

REST是&#39;准​​系统&#39; API,为您提供Google云端硬盘的全部功能。您还有一个交互式游乐场来测试所有内容(请参阅the bottom of this page)。但是你必须自己管理网络延迟,故障等。理想情况下,您将委派该工作以同步适配器服务。

GDAA构建于REST之上,驻留在Google Play服务中,并作为本地API运行,并将对象(文件夹/文件)推迟到云端硬盘。与REST相比仅具有有限的功能(忘记缩略图链接等...)。从本质上讲,您可以与GDAA和GDAA根据自己的时间表与Drive进行对话。因此,您不必担心在线/离线情况。但要小心,这可能也会导致同步问题,因为您无法直接控制对象提升时间。可以找到GDAA的演示herehere

我还创建了一个简单的CRUD demo app,您可以单步执行。您要求的上传位于create()方法中。它并不完全是最新的,因为GDAA实施了“垃圾”。已有功能(在Google Play Services 7.00 / Rev.2中)。

祝你好运