Android Google Drive API 身份验证

标签 android google-drive-api

我在我的 Android 应用程序上使用 Google Drive API 时遇到问题。在我的设备上,一台装有 Android 5.1.1 的 Nexus 4 运行良好。在我用户的设备上,我配置的同意屏幕没有显示,相反,只显示了一个包含用户电子邮件的列表选择对话框,但它没有执行任何操作。

我在其他装有 Android 5.0.1 的设备上看到了这个问题。

我使用生产 SHA1 key 和同意屏幕配置了 OAuth 2.0 凭据。正如我所说,它在我的设备上运行良好。

我正在使用以下参数来编译我的应用:

  • minSdkVersion=15
  • targeSdKVerion=22
  • compileSdkVersion=22
  • 构建工具:22.0.1
  • 平台工具:23rc3

还有这些谷歌库:

  • com.android.support:support-v4:22.2.0
  • com.android.support:appcompat-v7:22.2.0
  • com.android.support:design:22.2.0
  • com.google.android.gms:play-services-ads:7.5.0
  • com.google.android.gms:play-services-drive:7.5.0

谢谢!

这是我的代码现在的样子:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_RESOLUTION) {
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect.
            if (!mBackupAsyncTask.getGoogleApiClient().isConnecting() &&
                    !mBackupAsyncTask.getGoogleApiClient().isConnected()) {
                // Connect and execute the task.
                mBackupAsyncTask.getGoogleApiClient().connect();
            }
        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(LOG_TAG, "GoogleApiClient connection failed: " + connectionResult.toString());

    if (!connectionResult.hasResolution()) {
        Log.i(LOG_TAG, "Error with no resolution.");
        // Show the localized error dialog.
        GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0).show();
    } else {
        // The failure has a resolution. Resolve it.
        // Called typically when the app is not yet authorized, and an authorization
        // dialog is displayed to the user.
        try {
            connectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (IntentSender.SendIntentException e) {
            Log.e(LOG_TAG, "Exception while starting resolution activity.", e);
        }
    }
}

public class DriveBackupAsyncTask extends ApiClientAsyncTask<Object, Void, Metadata> {

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressBar.setIndeterminate(true);
        mEfetuarBackupButton.setEnabled(false);
        mRestaurarBackupButton.setEnabled(false);
    }

    @Override
    protected Metadata doInBackgroundConnected(Object... params) {
        if (params[0].equals(TASK_BACKUP)) {
            DriveFile backupFile = DriveBackupHelper.createBackup(
                    getGoogleApiClient(),
                    APP_FOLDER,
                    BACKUP_FILE,
                    getDbFile());

            if (backupFile != null)
                return backupFile.getMetadata(getGoogleApiClient()).await().getMetadata();
        }

        if (params[0].equals(TASK_RESTAURAR)) {
            DriveFile backupFile = DriveBackupHelper.getBackupFile(
                    getGoogleApiClient(),
                    APP_FOLDER,
                    BACKUP_FILE);

            if (backupFile == null)
                return null;

            if (DriveBackupHelper.restoreBackup(getGoogleApiClient(), getDbFile(), backupFile))
                return backupFile.getMetadata(getGoogleApiClient()).await().getMetadata();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Metadata result) {
        super.onPostExecute(result);
        mProgressBar.setIndeterminate(false);
        mEfetuarBackupButton.setEnabled(true);
        mRestaurarBackupButton.setEnabled(true);

        if (result == null) {
            showError(getString(R.string.bkp_error));
        } else {
            showMessage(getString(R.string.bkp_success));
        }
    }
}

最佳答案

此说明假定您的代码基于 Google API Guide用于处理连接失败,其结构类似于下面显示的示例(这是从指南中复制的):

@Override
public void onConnectionFailed(ConnectionResult result) {
    if (mResolvingError) {
        // Already attempting to resolve an error.
        return;
    } else if (result.hasResolution()) {
        try {
            mResolvingError = true;
            // This statement causing posting of the account picker dialog
            // or other UI to resolve the connection problem.
            result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
        } catch (SendIntentException e) {
            // There was an error with the resolution intent. Try again.
            mGoogleApiClient.connect();
        }
    } else {
        // Show dialog using GooglePlayServicesUtil.getErrorDialog()
        showErrorDialog(result.getErrorCode());
        mResolvingError = true;
    }
}

您看到的对话框是在用户需要选择帐户时创建的。它由 onConnectionFailed() 中的以下语句生成:

result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);

其中 REQUEST_RESOLVE_ERROR 是您定义的整数常量。当用户在对话框中选择一个帐户时,您的 Activity 会收到请求代码等于 REQUEST_RESOLVE_ERROR 的结果。您的 Activity 必须有一个方法来处理与此类似的结果(也从指南中复制):

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_RESOLVE_ERROR) {
        mResolvingError = false;
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mGoogleApiClient.isConnecting() &&
                    !mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }
        }
    }
}

当您在您的帖子中说该对话框“不执行任何操作”时,这表明您没有 onActivityResult() 方法,或者如果有,则代码不存在正确处理对话框的结果。

如果此答案对您没有帮助并且您已经有一个 onActivityResult(),请将其与 onConnectionFailed() 一起发布。

关于Android Google Drive API 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31123681/

相关文章:

java - 如何使用 android 从 Nest API 检索 Json 对象

android - 将包/路径设置为生成的 R.java

python - Google 云端硬盘断点续传上传失败

android - Gradle新版本和Build版本

android - 仅在使用 Proguard 的 Release模式下内存泄漏

Android Java : Fatal exception main nullpointer. 我没有明确定义的线程。它说它无法实例化 Activity

google-apps-script - 无法打开 Google xlsx 电子表格/Google Drive 权限也被阻止

google-api - 如何在 Drive API 中获取 google doc 修订的详细列表

python - OAuth API Google 云端硬盘 Python

javascript - Google Drive API,无法通过 JS 打开标准共享对话框(x-frame-options 错误)