GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIRED

扶醉桌前 提交于 2019-12-21 02:34:46

问题


I'm trying to connect my app to Google play service to access Google Drive but It showing me connection failed with statusCode SIGN_IN_REQUIRED.

But it seems to behave like that just 3 days ago. I am also checked developer console of google. They may have changed something in the API which i am unable to figure out. Your help will be welcome.

My Code:

/**
 * 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);
    }
}

/END OF CODE/

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 Message:

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

回答1:


Well i got the messages displayed in the LogCat:

GoogleApiClient onConnectionFailed with statusCode=SIGN_IN_REQUIRED

Sign in required means that we need to enable the Google Drive API https://console.developers.google.com

Download the client_id.json file and add into the /app folder of our project:

Then we can access with no problem, to get our expected API client connected.:

For a better use of Google Drive API, this permissions are suggested:

<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" />

You can find a complete example here:

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




回答2:


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.




回答3:


This error indicates that the account is locked, possibly for security reasons. You should go to drive.google.com from a desktop browser and log into the account before attempting to programmatically access the account via an Android app. Once you've gone all the way through a desktop browser login you should then be able to access the account from Android.




回答4:


This will work once you have created your Google API project, you have added your SHA-1 and Package Name as asked. Also, keep in mind that your package must not conflict with other projects in Google. Hope this works. Register your project in :

Click here to add enable your Google api

and enable API once project credentials are all set. And if you are looking to upload or download your files then you have to use Permissions in your Manifest file:

<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" />

-Surajit. Happy Coding.




回答5:


As I see most of the answer above are right, still if you could not able to solve the problem. Here are the things please check with your development environment

  1. If you have switched between two different systems(pc/laptop), please generate another SHA1 key for each system and update on Google developer console

  2. If you have not switched between two system still you face the issue then, make sure in your manifest application Id is matching with package name you have given in Google developer console

  3. Don't forget to enable Drive API in Google developer console




回答6:


i have same problem and spent a lot of time to fix

maybe you didn't add your email to testers list on google console or maybe your device google play games app signed in with another account so add it to testers accounts and try again

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

Game Services -> Testing.



来源:https://stackoverflow.com/questions/37185464/googleapiclient-onconnectionfailed-with-statuscode-sign-in-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!