如何使用Google drive api打开文件

时间:2015-06-27 04:53:08

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

我正在努力访问我的应用中的谷歌驱动器文件和文件夹。我想在从谷歌驱动器api中选择后打开一个文件。但我无法打开此文件。我使用了https://github.com/googledrive/android-demos/tree/master/src/com/google/android/gms/drive/sample/demo链接。我的代码如下。

public class RetrieveContentsActivity extends BaseDemoActivity {

private static final String TAG = "RetrieveContentsActivity";

@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint);
    Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
            .setResultCallback(idCallback);
}

final private ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
    @Override
    public void onResult(DriveIdResult result) {
        new RetrieveDriveFileContentsAsyncTask(
                RetrieveContentsActivity.this).execute(result.getDriveId());
    }
};

final private class RetrieveDriveFileContentsAsyncTask
        extends ApiClientAsyncTask<DriveId, Boolean, String> {

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

    @Override
    protected String doInBackgroundConnected(DriveId... params) {
        String contents = null;
        DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(), params[0]);
        DriveContentsResult driveContentsResult =
                file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
            return null;
        }
        DriveContents driveContents = driveContentsResult.getDriveContents();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(driveContents.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            contents = builder.toString();
        } catch (IOException e) {
            Log.e(TAG, "IOException while reading from the stream", e);
        }

        driveContents.discard(getGoogleApiClient());
        return contents;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result == null) {
            showMessage("Error while reading from the file");
            return;
        }
        showMessage("File contents: " + result);
    }
}

}
提前谢谢。

0 个答案:

没有答案