从谷歌驱动器列表中的文件,并得到downloadUrl在Android的选定文件 [英] List files from Google Drive and get downloadUrl for selected file in Android

查看:252
本文介绍了从谷歌驱动器列表中的文件,并得到downloadUrl在Android的选定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图表现出的文件列表,用户对从我的Andr​​oid应用程序的谷歌驱动器,一旦用户选择了一个文件,我想获得 downloadUrl 承载标记该帐户把它送给我的应用程序服务器上下载它。

I am trying to show a list of files the user has on their Google Drive from my Android app and once the user has selected a file, I want to get the downloadUrl and the Bearer token for that account to give it to my application server to download it.

我一直环顾四周,似乎很混乱。有2个SDK, Android SDK中并的 Java SDK的 REST 开始),谷歌驱动器。

I have been looking around and it seems very confusing. There are 2 SDKs, Android SDK and Java SDK (REST based) for Google Drive.

我成功是能够得到的文件列表,并使用Android SDK(我没有构建任何UI)显示它,当用户选择了一个文件,我得到了所有的有关文件,但 downloadUrl 。我没有得到一些链接,如 webContentLink alternateLink ,但事实证明,由于文件没有共享,我无法通过这些链接到我的服务器下载。

I successfully was able to get the list of files and display it using the Android SDK (I did not have to build any UI), and when the user selects a file, I got all the metadata about the file but the downloadUrl. I did get some links like the webContentLink and the alternateLink, but it turns out that because the file was not shared, I cannot pass these links to my server to download it.

当一些更多的研究,我发现,在 downloadUrl 是使用Java SDK进行访问。我的问题是,我必须建立自己的用户界面来显示文件,我得到的名单?如何处理的文件夹层次,如果我要建立我的UI显示这些文件?

Upon some more research I found out that the downloadUrl is accessible by using the Java SDK. My question is, do I have to build my own UI to display a list of files I obtain? How do I handle the folder hierarchy if I have to build my UI to show these files?

下面是code它打印有关文件中的数据。我已经实现在此基础上code中的教程

Below is the code which prints the data about the File. I have implemented this code based on the tutorial.

public class GoogleDriveActivity extends Activity {

private GoogleApiClient mGoogleApiClient;
public com.google.api.services.drive.Drive mService;
public GoogleAccountCredential credential;
public static final int REQUEST_AUTHORIZATION = 3;
public static final int REQUEST_ACCOUNT_PICKER = 4;

private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = {DriveScopes.DRIVE_METADATA_READONLY};
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google_drive);

    SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
    credential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff())
            .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, "abc.test@gmail.com"));

    mService = new com.google.api.services.drive.Drive.Builder(
            transport, jsonFactory, credential)
            .setApplicationName("My Application")
            .build();
}

@Override
public void onResume() {
    super.onResume();
    refreshResults();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_AUTHORIZATION:
            if (resultCode != RESULT_OK) {
                chooseAccount();
            }
            break;
        case REQUEST_ACCOUNT_PICKER:
            Log.w("gd", "in account picker");
            if (resultCode == RESULT_OK && data != null &&
                    data.getExtras() != null) {
                String accountName =
                        data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) {
                    credential.setSelectedAccountName(accountName);
                    SharedPreferences settings =
                            getPreferences(Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(PREF_ACCOUNT_NAME, accountName);
                    editor.commit();
                }
            } else if (resultCode == RESULT_CANCELED) {
                Log.W("gd", "in cancelled");
            }
            break;

        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void chooseAccount() {
    startActivityForResult(
            credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}

private void refreshResults() {
    new GoogleDriveAsync(this).execute();
}

public class GoogleDriveAsync extends AsyncTask<Void, Void, Void> {

    private GoogleDriveActivity activity;

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            getDataFromApi();

        } catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
            Log.w("gd", "GPS unavailable");

        } catch (UserRecoverableAuthIOException userRecoverableException) {
            Log.w("gd", "user recoverable");
            activity.startActivityForResult(
                    userRecoverableException.getIntent(),
                    GoogleDriveActivity.REQUEST_AUTHORIZATION);

        } catch (Exception e) {
            Log.w("gd", "general exception " + e.getMessage());
        }
        return null;
    }

    GoogleDriveAsync(GoogleDriveActivity activity) {
        this.activity = activity;
    }

    /**
     * Fetch a list of up to 10 file names and IDs.
     *
     * @return List of Strings describing files, or an empty list if no files
     * found.
     * @throws IOException
     */
    private List<String> getDataFromApi() throws IOException {
        // Get a list of up to 10 files.
        List<String> fileInfo = new ArrayList<String>();
        FileList result = activity.mService.files().list()
                .setMaxResults(10)
                .execute();
        List<File> files = result.getItems();
        if (files != null) {
            for (File file : files) {
                fileInfo.add(String.format("%s (%s) (%s)\n",
                        file.getTitle(), file.getId(), file.getDownloadUrl()));
            }
        }
        Log.w("gd", "file info is " + fileInfo.toString());
        return fileInfo;

    }
}
}

编辑:请参阅我的工作示例答案(而不是接受一个)。用例是:列出所有用户的谷歌云端硬盘文件,并选择了一个时,获得 downloadUrl 的access_token 该文件。

推荐答案

为了使用您的GDAA基于应用程序之外的文件/文件夹,你需要所谓的ResourceID。这RESOURCEID是唯一标识谷歌Drive的对象的字符串(请参阅here)

In order to use the file/folder outside of your GDAA based app, you need so-called ResourceID. This ResourceId is a string that uniquely identifies the object of Google Drive (see here)

打开驱动器Id到RESOURCEID:

Turn DriveId into ResourceId:

        DriveId driveId = metadata.getDriveId();
        String resourceId = driveId.getResourceId();

一旦你有了RESOURCEID,可以构建'下载网址从它的服务器应用程序。通过resourceID串中发现,如果你去 drive.google.com 之一,选择一个文件/文件夹并执行的 rightbutton> getLink 的。结果
(看起来像' https://drive.google.com/open?id=0B1mQUW2__I_am_the_resource_id ')

Once you have ResourceId, you can construct 'download URL' for your server app from it. The ResourceID string is the one found if you go to drive.google.com, select a file/folder and perform rightbutton > getLink.
(looks like 'https://drive.google.com/open?id=0B1mQUW2__I_am_the_resource_id')

只是借此字符串'的 0B1mQUW2__I_am_the_resource_id 的'到 TryIt'操场这里并粘贴到FILEID字段。

Just take this string '0B1mQUW2__I_am_the_resource_id' to the 'TryIt' playground here and paste it to the 'fileId' field.

所以,简单的答案是,你并不需要的RESTful API来让你可以在其他地方使用的文件/文件夹的标识符。

So, the short answer is that you don't need RESTful Api to get the file/folder identifier you can use elsewhere.

你的问题的第二部分,如何处理的文件夹层次,如果我要建立我的UI显示这些文件的?在回答(有点)在createTree()/ testTree()'MainActivity的方法,这2演示( GDAADemo RESTDemo )。以上是关于GDAA还有REST API的实现相同的任务而选择主要取决于SCOPE您的应用程序的需求(GDAA仅支持文件范围,而REST支持的文件和驱动范围)

Second part of your question, 'How do I handle the folder hierarchy if I have to build my UI to show these files?' is answered (somewhat) in the 'createTree()/testTree()' methods of MainActivity of these 2 demos (GDAADemo, RESTDemo). These are the same tasks implemented on the GDAA as well as the REST Apis and the choice depends mainly on the SCOPE your app needs (GDAA supports only the FILE scope, whereas REST supports both the FILE and the DRIVE scopes)

好运

这篇关于从谷歌驱动器列表中的文件,并得到downloadUrl在Android的选定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆