【问题标题】:GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIREDGoogleApiClient onConnectionFailed 与 statusCode=SIGN_IN_REQUIRED
【发布时间】:2016-05-12 11:24:08
【问题描述】:

我正在尝试将我的应用连接到 Google Play 服务以访问 Google 云端硬盘,但它显示 连接失败 状态代码为 SIGN_IN_REQUIRED.

但它的行为似乎就在 3 天前。我还检查了谷歌的开发者控制台。他们可能在 API 中更改了一些我无法弄清楚的内容。欢迎您的帮助。

我的代码:

/**
 * Create a new file and save it to Drive.
 */
    private void saveFileToDrive(final byte[] data) {
    // Start by creating a new contents, and setting a callback.
    Log.i(TAG, "Creating new contents.");
    //final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(mGoogleApiClient)
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {

                @Override
                public void onResult(DriveApi.DriveContentsResult result) {
                    // If the operation was not successful, we cannot do anything
                    // and must
                    // fail.
                    if (!result.getStatus().isSuccess()) {
                        Log.i(TAG, "Failed to create new contents.");
                        return;
                    }
                    // Otherwise, we can write our data to the new contents.
                    Log.i(TAG, "New contents created.");
                    // Get an output stream for the contents.
                    OutputStream outputStream = result.getDriveContents().getOutputStream();
                    // Write the bitmap data from it.
                   /* ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
                    image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);*/
                    try {
                        //outputStream.write(bitmapStream.toByteArray());
                        outputStream.write(data);
                    } catch (IOException e1) {
                        Log.i(TAG, "Unable to write file contents.");
                    }
                    // Create the initial metadata - MIME type and title.
                    // Note that the user will be able to change the title later.
                    MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                            .setMimeType("application/pdf").setTitle(filename).build();
                    // Create an intent for the file chooser, and start it.
                    IntentSender intentSender = Drive.DriveApi
                            .newCreateFileActivityBuilder()
                            .setInitialMetadata(metadataChangeSet)
                            .setInitialDriveContents(result.getDriveContents())
                            .build(mGoogleApiClient);
                    try {
                        startIntentSenderForResult(
                                intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i(TAG, "Failed to launch file chooser.");
                    }
                }
            });
}

@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();

}



@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_CODE_CREATOR:
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Image successfully saved.");

                Intent intent = new Intent();
                intent.putExtra("FILE_PATH",file_path);
                PreviewActivity.this.setResult(RESULT_OK, intent);
                finish();
                progressDialog.hide();

            }
            break;
    }
}

@Override
public void onConnected(Bundle bundle) {

    Log.i(TAG, "API client connected.");
    //saveFileToDrive();
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "GoogleApiClient connection suspended");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    // Called whenever the API client fails to connect.
    Log.i(TAG, "GoogleApiClient connection failed: " + connectionResult.toString());
    if (!connectionResult.hasResolution()) {
        // show the localized error dialog.
        GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), 0).show();
        return;
    }
    // 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(TAG, "Exception while starting resolution activity", e);
    }
}

/代码结束/

分级:

apply plugin: 'com.android.application'

android {


dexOptions {
    incremental true
    javaMaxHeapSize "2048M"

}

compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
    multiDexEnabled true
    applicationId "com.woundcentrics.abxsteward"
    minSdkVersion 14
    targetSdkVersion 21
    versionCode 1
    versionName "0.4 (Beta)"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/DEPENDENCIES'
}
productFlavors {
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'org.robolectric:robolectric:3.0'
compile project(':openCVLibrary310')
compile files('libs/itextpdf-5.1.0.jar')
compile project(':scanlibrary')
apply plugin: 'com.google.gms.google-services'
compile 'me.dm7.barcodescanner:zbar:1.8.3'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'com.google.code.gson:gson:2.4'
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.google.android.gms:play-services-ads:8.3.0'
compile 'com.google.android.gms:play-services-identity:8.3.0'
compile 'com.google.android.gms:play-services-gcm:8.3.0'

}
repositories {
jcenter()

}

Logcat 消息:

GoogleApiClient connection failed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{21d08740: android.os.BinderProxy@21d032b8}, message=null}

【问题讨论】:

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


    【解决方案1】:

    我得到了 LogCat 中显示的消息:

    GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIRED

    需要登录意味着我们需要启用 Google Drive API https://console.developers.google.com

    下载client_id.json文件并添加到我们项目的/app文件夹中:

    那么我们就可以毫无问题地访问,得到我们期望的API client connected.

    为了更好地使用 Google Drive API,建议使用以下权限:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    

    你可以在这里找到一个完整的例子:

    https://github.com/Jorgesys/Android-Google-Drive

    【讨论】:

    • 为什么client_id.json 文件甚至在构建期间打包?
    • 谢谢,这就是我要找的东西
    【解决方案2】:

    我有同样的问题,花了很多时间来解决

    也许你没有将你的电子邮件添加到谷歌控制台上的测试人员列表中,或者你的设备谷歌玩游戏应用程序使用另一个帐户登录,所以将其添加到测试人员帐户并重试

    https://play.google.com/apps/publish

    游戏服务 -> 测试。

    【讨论】:

      【解决方案3】:

      Here 是您收到的错误信息。我假设您是,但您需要登录才能访问云端硬盘。当我运行示例应用程序时,一开始它要求我选择一个帐户。也许您没有与您正在使用的设备同步的帐户?有一个“添加帐户”选项,但当您的帐户为零时,行为可能会有所不同。文档建议您不使用 API 继续(只是因为除非您登录,否则您不能)或调用 startResolutionForResult(Activity, int) 提示用户登录,但最简单的方法可能是添加 account to your device .

      【讨论】:

      • 感谢您的快速回复。实际上它早些时候工作正常。但它的行为似乎就在 3 天前。我还检查了谷歌的开发者控制台。他们可能在 API 中改变了一些我无法弄清楚的东西。欢迎您的帮助。再次感谢。
      • 我只想添加一些指针来跟进@Krishna 的回答。您只需将处理程序添加到 Google Drive API 的连接和授权中。这可以通过GoogleApiClient 完成。这应该在OnCreate() 方法中找到。您可以尝试阅读connecting for authorization 上的实施指南以进行澄清。这可能会解决您的 GoogleApiClient 连接失败的问题。我希望这有帮助。 :)
      • @AbdulYasin Iam 面临同样的问题。我的应用程序运行良好,直到今天,但现在我无法登录。选择帐户继续询问,它返回 Google api 客户端失败结果代码 4。我没有改变了任何东西。提前谢谢:)
      【解决方案4】:

      此错误表明帐户已被锁定,可能是出于安全原因。在尝试通过 Android 应用程序以编程方式访问该帐户之前,您应该从桌面浏览器转到 drive.google.com 并登录该帐户。完成桌面浏览器登录后,您应该能够从 Android 访问该帐户。

      【讨论】:

      • 帐户在移动和网络浏览器上都可以正常工作。
      【解决方案5】:

      一旦您创建了 Google API 项目,您就可以按照要求添加您的 SHA-1 和包名称。 另外,请记住,您的包不得与 Google 中的其他项目发生冲突。 希望这有效。 在以下位置注册您的项目:

      Click here to add enable your Google api

      并在项目凭据全部设置后启用 API。 如果您要上传或下载文件,则必须在清单文件中使用权限:

      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.GET_ACCOUNTS" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      

      -苏拉吉特。 快乐编码。

      【讨论】:

        【解决方案6】:

        正如我所见,上面的大多数答案都是正确的,但如果您无法解决问题。以下是请检查您的开发环境的内容

        1. 如果您在两个不同的系统(PC/笔记本电脑)之间切换,请为每个系统生成另一个 SHA1 密钥并在 Google 开发者控制台上更新 p>

        2. 如果您还没有在两个系统之间切换,那么您仍然会遇到问题,请确保您的清单中的 应用程序 ID 与您提供的 包名称 匹配在 Google 开发者控制台中

        3. 别忘了在 Google 开发者控制台中启用 Drive API

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-15
          相关资源
          最近更新 更多