2015-10-06 200 views
2

我有以下代碼來獲取Google雲端硬盤中文件的DriveContents。我能夠導入並獲取MS Word,文本文件等的DriveContents,但是當文件是Google(Google Doc,Google表格等)原生文件時,我無法獲取內容。我的代碼如下:Google雲端硬盤導入Google文檔

selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() { 
    public void onResult(DriveApi.DriveContentsResult result) { 
     try { 
      if (!result.getStatus().isSuccess()) { 
       // display an error saying file can't be opened 
       Log.e(TAG, "Could not get file contents"); 
       return; 
      } 

      // DriveContents object contains pointers 
      // to the actual byte stream 
      DriveContents contents = result.getDriveContents(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream())); 
      StringBuilder builder = new StringBuilder(); 
      String line; 
      try { 
       while ((line = reader.readLine()) != null) { 
        builder.append(line); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      String contentsAsString = builder.toString(); 

      contents.discard(getGoogleApiClient()); 

      Log.i(TAG, contentsAsString); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
}); 

每當我收到了谷歌格式的文件,它只是返回一個結果是不是成功,並顯示在我的日誌中的錯誤。我怎樣才能獲得這些文件的文件內容?有什麼特別的我應該做的?

我閱讀下列文件:如果

​​

回答

2

不知道這是最好的解決辦法,但我做到了下面的方法。我檢查元數據,如果它是一個谷歌格式(文檔,牀單等),如果是,我有一個AsyncTask,做以下:

// accountName is the email address the user used when choosing which account 
String scope = "oauth2:https://www.googleapis.com/auth/drive.file"; 
token = GoogleAuthUtil.getTokenWithNotification(fragment.getActivity(), accountName, scope, null); 

做好以上後,您可以使用獲取文件API:

https://developers.google.com/drive/web/manage-downloads

從上述的token給出關於下載的Authentication頭令牌。我們可以將文件導出爲docx,pdf等,並以此方式下載。

相關問題