GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIRED

GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIRED

我正在尝试将我的应用程序连接到 Google 播放服务以访问 Google 驱动器,但它向我显示 连接失败,状态代码为 SIGN_IN_REQUIRED.

但它似乎就在 3 天前表现得像那样。我还检查了 google 的开发者控制台。他们可能更改了 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);
    }
}

/代码结束/

Gradle:

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}

Here is the info for the error you are receiving. I assume you are, but you need to be signed in to access Drive. When I run the sample app, at the very beginning it asks me to choose an account. Perhaps you do not have an account synced with the device you are using? There is an option to "add account", but maybe the behaviour is different when you have zero accounts. The documentation suggests that you either continue without using the API (simply because you cannot unless you sign in) or call startResolutionForResult(Activity, int) to prompt the user to sign in, but it would probably be easiest to just add the account to your device.

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

访问该帐户

这将在您创建 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" />

-苏拉吉特。 快乐编码。

好吧,我收到了 LogCat 中显示的消息:

GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIRED

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

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

然后就可以正常访问了,得到我们预期的API client connected.:

为了更好地使用 Google 驱动器 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

我看到上面的大部分答案都是正确的,但如果您无法解决问题。以下是请检查您的开发环境

  1. 如果您在两个不同的系统之间切换(pc/laptop),请生成另一个SHA1密钥 为每个系统更新 Google 开发者控制台

  2. 如果您还没有在两个系统之间切换,那么您仍然会遇到问题,请确保您的清单中的 application Id 匹配您在 Google 开发者控制台

  3. 中提供的软件包名称
  4. 别忘了在Google开发者控制台

  5. 启用云端硬盘API

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

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

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

游戏服务 -> 测试。