首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有替代方法: Drive.getDriveClient(),Drive.getDriveResourceClient,...来自已弃用的api?

有没有替代方法: Drive.getDriveClient(),Drive.getDriveResourceClient,...来自已弃用的api?
EN

Stack Overflow用户
提问于 2019-06-11 16:29:15
回答 1查看 748关注 0票数 1

代码中不推荐使用的方法(如下所示)使得将Google Drive Picker集成到Android应用程序成为可能。

代码语言:javascript
运行
复制
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。但安全部队是通过android.net.Uri工作的。它允许获取文件名,但不提供文件ID。

代码语言:javascript
运行
复制
    /**
     * 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:

代码语言:javascript
运行
复制
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?

我可以用什么来替换过时的方法来保留程序的功能?你有什么建议?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-11 17:49:38

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

代码语言:javascript
运行
复制
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()
        );
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56539510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档