как создать файл для загрузки на Google Диск в приложении для Android

Я реализовал функцию загрузки файла на Google Диск. Мое приложение (приложение для Android) имеет две страницы.

Страница настроек: мы настроили учетную запись Google. После входа в аккаунт Google. Мы предоставляем право и сохраняем OAUTH_TOKEN и OAUTH_TOKEN_SECRET в SharedPreferences.

Загрузить страницу: Выбираем файлы из проводника. Затем нажмите кнопку [ЗАГРУЗИТЬ], чтобы отправить их на Google Диск.

Я нашел пример кода на developer.google.com, чтобы показать, как загрузить файл. Это выглядит так


/**
   * Insert new file.
   *
   * @param service Drive API service instance.
   * @param title Title of the file to insert, including the extension.
   * @param description Description of the file to insert.
   * @param parentId Optional parent folder's ID.
   * @param mimeType MIME type of the file to insert.
   * @param filename Filename of the file to insert.
   * @return Inserted file metadata if successful, {@code null} otherwise.
   */
  private static File insertFile(Drive service, String title, String description,
      String parentId, String mimeType, String filename) {
    // File's metadata.
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);

    // Set the parent folder.
    if (parentId != null && parentId.length() > 0) {
      body.setParents(
          Arrays.asList(new File.ParentReference().setId(parentId));
    }

    // File's content.
    java.io.File fileContent = new java.io.File(filename);
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    try {
      File file = service.files().insert(body, mediaContent).execute();

      // Uncomment the following line to print the File ID.
      // System.out.println("File ID: %s" + file.getId());

      return file;
    } catch (IOException e) {
      System.out.println("An error occured: " + e);
      return null;
    }
  }

Поэтому мы просто вызываем вышеуказанную функцию для загрузки файла. Но я не знаю, как инициализировать диск (com.google.api.services.drive.Drive) для перехода к функции.

Что мне нужно сделать, чтобы инициализировать переменную привода с помощью OAUTH_TOKEN и OAUTH_TOKEN_SECRET?

Спасибо за вашу помощь.


person quantm    schedule 13.09.2012    source источник
comment
Как инициализировать службу в этом методе, как я могу сохранить аутентификацию   -  person Karthick M    schedule 02.01.2015
comment
Привет, @quantm, у тебя есть ответ на этот вопрос? Не могли бы вы загрузить файл на Google Диск в приложении для Android?   -  person user4232    schedule 18.09.2015


Ответы (1)


На странице OAuth 2.0 в документации Google Drive SDK объясняется, как получить действительные учетные данные и использовать их для создания экземпляра объекта службы:

https://developers.google.com/drive/credentials

person Claudio Cherubino    schedule 13.09.2012
comment
как загружать файлы программно, как использовать этот сервис для загрузки файлов - person Karthick M; 02.01.2015