Art*_*are 58 android google-drive-api
我花了最后六个小时倾注了谷歌的文件,我仍然不知道如何开始这个.我想做的就是让我现有的Android应用可以从Google云端硬盘读取文件,将新文件上传到Google云端硬盘,以及修改Google云端硬盘上的现有文件.
我已经读过Drive SDK v2专注于让Android(以及一般移动设备)开发人员可以轻松使用它,但他们的文档中几乎没有关于它的内容.
理想情况下,我希望有人指出一些体面的文档,示例或教程,介绍如何执行此操作(请记住,我正在使用Android.他们有很多关于如何使用Google App Engine的驱动程序;我有已经看过它,我不知道如何从那个到Android应用程序.)
我需要知道我需要下载哪些库并添加到我的项目中,我需要添加到我的清单中,以及如何最终从Google云端硬盘获取文件列表,下载一个,然后上传修改后的版本.
理想情况下,我希望它能够自动处理帐户,就像官方Google云端硬盘应用程序所做的那样.
Art*_*are 80
编辑:克劳迪奥·切鲁比诺说,谷歌播放服务现已上市,将使这一过程变得更加容易.但是,没有可用的示例代码(但是,他说它即将推出......他们说Google Play服务在4个月前"即将推出",所以这个答案很可能会继续成为访问的唯一完整工作示例从您的Android应用程序到2013年的Google云端硬盘.)
编辑2X:看起来我已经离开了大约一个月,当时我说Google直到明年才会有一个有效的例子.谷歌的官方指南就在这里:
https://developers.google.com/drive/quickstart-android
我还没有测试过他们的方法,所以从2012年9月(下面)我的解决方案仍然是最好的:
Google Play服务不需要这样做.这是一个痛苦的屁股,我花了超过50个小时(编辑:100多个小时)搞清楚,但这里有很多事情,这将有助于知道:
图书馆
对于Google的在线服务,您通常需要在项目中使用这些库:( 说明和下载链接)
特别是对于Google云端硬盘,您还需要:
设置控制台
接下来,转到Google控制台.制作一个新项目.在服务下,您需要打开两件事:DRIVE API和DRIVE SDK!它们是分开的,一个不会自动转动另一个,你必须同时打开!(弄清楚这一点至少浪费了我20个小时的时间.)
仍在控制台上,转到API Access.创建一个客户端,使其成为Android应用程序.给它你的包ID.我不认为指纹的东西实际上很重要,因为我很确定我使用了错误的指纹,但是无论如何都要尝试做到这一点(Google为它提供了说明.)
它会生成一个客户端ID.你需要那个.抓住它.
编辑:我被告知我错了,您只需打开Drive API,根本不需要打开Drive SDK,而您只需要使用Simple API Key,而不是设置适用于Android的东西.我现在正在研究这个问题,如果我弄明白的话,可能会在几分钟后编辑这个答案......
ANDROID代码 - 设置和上传
首先,获取身份验证令牌:
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
Run Code Online (Sandbox Code Playgroud)
接下来,OnTokenAcquired()需要设置如下:
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...
}
}
}
Run Code Online (Sandbox Code Playgroud)
ANDROID代码 - 下载
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;
}
}
Run Code Online (Sandbox Code Playgroud)
最后一件事......如果该意图被发送出去,你需要在返回结果时进行处理.
@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.
}
}
Run Code Online (Sandbox Code Playgroud)
ANDROID代码 - 更新
关于更新Google云端硬盘上文件上次修改日期的两个快速说明:
以下是一些简短的示例代码,展示了如何进行更新,包括更新文件时间:
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();
}
Run Code Online (Sandbox Code Playgroud)
清醒
您需要以下权限:GET_ACCOUNTS,USE_CREDENTIALS,MANAGE_ACCOUNTS,INTERNET,并且您很可能还需要WRITE_EXTERNAL_STORAGE,具体取决于您希望存储文件的本地副本的位置.
你的建设目标
右键单击您的项目,进入它的属性,然后在Android下将构建目标更改为Google API(如果必须).如果它们不存在,请从android下载管理器下载它们.
如果您在模拟器上进行测试,请确保其目标是Google API,而不是通用Android.
您需要在测试设备上设置Google帐户.所写的代码将自动使用它找到的第一个Google帐户(这就是[0]所用的.)IDK,如果您需要下载Google云端硬盘应用程序才能使用此帐户.我使用的是API Level 15,我不知道这段代码能用多久.
其余的部分
上面的内容应该让你开始,希望你能从那里找到出路...老实说,这就是我到目前为止所做的一切.我希望这可以帮助很多人并为他们节省很多时间.我很确定我刚刚编写了最全面的设置指南,用于设置Android应用以使用Google云端硬盘.谷歌羞于在至少6个不相互链接的页面上传播必要的材料.
查看 Google I/O 大会上的这段视频,了解如何将 Android 应用与云端硬盘集成:
http://www.youtube.com/watch?v=xRGyzqD-vRg
请注意,您在视频中看到的内容基于 Google Play 服务:
https://developers.google.com/android/google-play-services/
2015年了,一切都变了!
使用 gradle 获取“Drive API for Android”:
compile 'com.google.android.gms:play-services-drive:7.8.0'
Run Code Online (Sandbox Code Playgroud)
有一些新的 doco(尽管在我看来仍然乏善可陈):
https://developers.google.com/drive/web/quickstart/android
对于那些即将去洞穴探险的人来说...到目前为止我遇到的最大问题是绝对没有办法区分已永久删除的文件夹和正常的文件夹...您可以找到它们,可以创建文件夹并内的文件,仅写入文件 DriveContents 将始终失败。
归档时间: |
|
查看次数: |
85548 次 |
最近记录: |