是否可以替换以下方法:Drive.getDriveClient(),Drive.getDriveResourceClient,...来自不推荐使用的api?

时间:2019-06-11 08:29:15

标签: java android google-drive-api

代码中不推荐使用的方法(如下)可以将Google Drive Driveer集成到Android应用程序中。

import com.google.android.gms.drive.Drive; // deprecated
import com.google.android.gms.drive.Drive; // deprecated
import com.google.android.gms.drive.DriveClient; // deprecated
import com.google.android.gms.drive.DriveFile; // deprecated
import com.google.android.gms.drive.DriveId; // deprecated
import com.google.android.gms.drive.DriveResourceClient; // deprecated
import com.google.android.gms.drive.Metadata; // deprecated
import com.google.android.gms.drive.OpenFileActivityOptions; // deprecated
import com.google.android.gms.drive.query.Filters; // deprecated
import com.google.android.gms.drive.query.SearchableField; // deprecated

    // ...

    /**
     * Handles high-level drive functions like sync
     */
    private DriveClient mDriveClient; // deprecated
    private Drive mDriveService; // deprecated

    /**
     * Handle access to Drive resources/files.
     */
    private DriveResourceClient mDriveResourceClient; // deprecated

    // ...

    /**
     * Continues the sign-in process, initializing the Drive clients with the current
     * user's account.
     */
    private void initializeDriveClient(GoogleSignInAccount signInAccount) {
        mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
        mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
        // ...
    }

    /**
     * Prompts the user to select a folder using OpenFileActivity.
     *
     * @param openOptions Filter that should be applied to the selection
     * @return Task that resolves with the selected item's ID.
     */
    private Task<DriveId> pickItem(OpenFileActivityOptions openOptions) {
        mOpenItemTaskSource = new TaskCompletionSource<>();
        getDriveClient()
                .newOpenFileActivityIntentSender(openOptions)
                .continueWith((Continuation<IntentSender, Void>) task -> {
                    startIntentSenderForResult(
                            task.getResult(), REQUEST_CODE_OPEN_ITEM,
                            null, 0, 0, 0);
                    return null;
                });
        return mOpenItemTaskSource.getTask();
    }

    /**
     * Handles resolution callbacks.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_OPEN_ITEM:
                if (resultCode == RESULT_OK) {
                    DriveId driveId = data.getParcelableExtra(
                            OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
                    mOpenItemTaskSource.setResult(driveId);
                    fileId = driveId.getResourceId();
                } else {
                    mOpenItemTaskSource.setException(
                            new RuntimeException("Unable to open file")
                    );
                }
                break;
                }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * To retrieve the metadata of a file.
     */
    private void retrieveMetadata(final DriveFile file) {
        Task<Metadata> getMetadataTask = getDriveResourceClient().getMetadata(file);
        getMetadataTask
                .addOnSuccessListener(this,
                        (Metadata metadata) -> {
                            showMessage(getString(
                                    R.string.metadata_retrieved, metadata.getTitle()));
                            fileName = metadata.getTitle();
                            sendDownloadAuthData();
                            finish();
                        })
                .addOnFailureListener(this, e -> {
                    Log.e(TAG, "Unable to retrieve metadata", e);
                    showMessage(getString(R.string.read_failed));
                    finish();
                });
    }

    protected DriveResourceClient getDriveResourceClient() {
        return mDriveResourceClient;
    }

    protected DriveClient getDriveClient() {
        return mDriveClient;
    }

在新的Drive Api v3中,我找不到允许保留程序功能的方法。 Google提供的其中一个示例建议使用SAF。但是SAF通过android.net.Uri运行。它允许获取文件的名称,但不提供文件ID。

    /**
     * Opens the file at the {@code uri} returned by a Storage Access 
       Framework {@link Intent}
     * created by {@link #createFilePickerIntent()} using the given 
       {@code contentResolver}.
     */
    public Task<String> getCurrentFileName(
            ContentResolver contentResolver, Uri uri) {
        return Tasks.call(mExecutor, () -> {
            // Retrieve the document's display name from its metadata.
            String currentName = "";
            try (Cursor cursor = contentResolver
                    .query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    Log.d(TAG, "cursor.getColumnCount(): " + 
                     cursor.getColumnCount());
                    for (int i = 0; i < cursor.getColumnCount(); i++) {
                        Log.d(TAG, i + " - " + cursor.getString(i) + 
                      "\n");
                    }
                    int nameIndex = 
                  cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    currentName = cursor.getString(nameIndex);
                } else {
                    throw new IOException("Empty cursor returned for 
               file.");
                }
            }

            return currentName;
        });
    }

该方法需要文件ID:

void downloadFile(String fileId) {
        try {
            java.io.File targetFile = new java.io.File(FULL_PATH_MD);
            mFileOutputStream = new FileOutputStream(targetFile);

            mDriveService.files()
                    .export(fileId, "text/csv")
                    .executeMediaAndDownloadTo(mFileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Utils.closeQuietly(mFileOutputStream, true);
        }
    }

该链接上问题的其他信息: How to migrate to Drive API v3 and get file ID for files.export?

我可以替换不推荐使用的方法以保留程序的功能吗?你有什么建议?

1 个答案:

答案 0 :(得分:0)

您可以通过Uri重命名文件,然后找到它并获取其文件ID。

public Uri renameFile(ContentResolver contentResolver, Uri uri, String newFilename) {
        Uri newLink = null;
        try {
            newLink = DocumentsContract.renameDocument(context, uri, newFilename);
        } catch (SecurityException e2) {
            e2.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return newLink;
    }

    Task<FileList> queryFile(String newFileName) {
        return Tasks.call(mExecutor, () ->
                service.files().list()
                    .setQ("mimeType='application/vnd.google-apps.spreadsheet'")
                    .setQ("fullText contains " + "'" + newFileName + "'")
                    .setQ("trashed = false")
                    .setFields("files(id, name)")
                    .execute()
        );
    }