谷歌驱动器API - 无法在Android应用程序中下载文件

时间:2014-05-19 16:34:39

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

我一直试图将google驱动器api与我的代码集成,以便上传和下载文本文件。我已成功设法上传文件,但下载时,输入流读取为空。

以下是我尝试上传的方式:

IntentSender intentSender = Drive.DriveApi
                    .newOpenFileActivityBuilder()
                    .setMimeType(new String[] { "text/plain" })
                    .build(mGoogleApiClient);
            try {
                startIntentSenderForResult(intentSender,
                        REQUEST_CODE_OPENER, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.w(TAG, "Unable to send intent", e);
            }

然后在onActivityResult中,这就是我正在做的事情:

DriveId driveId = (DriveId) data
                .getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
        showMessage(driveId.toString());

        DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
        Log.v(TAG, file.toString());

        file.openContents(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).setResultCallback(contentsOpenedCallback);
        new ReadContentsAsyncTask(MainMusicActivity.this).execute(file);

我的AsyncTask类看起来像这样

public class ReadContentsAsyncTask extends
        ApiClientAsyncTask<DriveFile, Void, Boolean> {

    public ReadContentsAsyncTask(Context context) {
        super(context);
    }

    @Override
    protected Boolean doInBackgroundConnected(DriveFile... args) {
        String contents = null;
        DriveFile file = args[0];
        ContentsResult contentsResult =
                file.openContents(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
        if (!contentsResult.getStatus().isSuccess()) {
            Log.v(TAG,  "RETURNINNG!!!");
            return null;
        }
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(contentsResult.getContents().getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            contents = builder.toString();
            Log.v(TAG,  contents); // its empty
        } catch (IOException e) {
            Log.e(TAG, "IOException while reading from the stream", e);
        }

        Log.v(TAG,  contents);
        file.discardContents(getGoogleApiClient(), contentsResult.getContents()).await();
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (!result) {
            showMessage("Error while editing contents");
            return;
        }
        showMessage("Successfully edited contents");
    }
}

我无法弄清楚为什么我无法读取文件内容。

一个令人困惑的情况是,当我从网上制作驱动器中的文本文件时,此代码运行正常。

非常感谢任何帮助。谢谢

0 个答案:

没有答案