Google Drive Android API ConnectionResult Error - android

I'm making an app and I'm integrating the Google Drive Android API into it. I have a main activity then a fragment that opens that leads to google drive. However, when I try to sign in (it doesn't matter what gmail account, I've tried existing ones, creating new ones, whatever) I get ConnectionResult error code 17 SIGN_IN_FAILED. The app is authorized in the developer console and the Drive API is enabled. I don't know what else to do.
Here is the relevant code:
public class FileSharingFragment extends Fragment implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_file_sharing, container, false);
users = (TextView) rootView.findViewById(R.id.users);
getActivity().setTitle("Files");
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == Activity.RESULT_OK) {
mGoogleApiClient.connect();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), getActivity(), 0).show();
Log.i("file sharing fragment", "error code " + result.getErrorCode());
return;
}
try {
result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
And to call it from the main activity I use
Fragment fragment = FileSharingFragment.newInstance();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
I cannot for the life of me figure out why it won't let me sign in.

You probably know by now that your Developers Console needs 3 things:
1/ SHA1 of yout APK
2/ your package name
3/ your email/product name in the Consent Screen
Assuming everything is OK there, here's the last-resort double-check I use often:
- open (unzip) your xxxx.APK using unzipper (like 7zip), find CERT.RSA.
- run 'keytool -printcert -file .........\CERT.RSA'
Go back to the console and compare the SHA1's again.
Good Luck

It might seem obvious but if you've entered your fingerprint on the developer console and set up your API there and are still getting SIGN_IN_FAILED make sure you are actually using the signed APK!
It's too easy to run installDebug from Gradle and forget. I usually set it up and go through the menus (Build > Generate Signed APK...) in Android Studio when I'm working with Google SDK's

Over the Google Developers Console go to API & Auth -> Credentials and check the Package name is exactly the same that your Application Package name.

Make sure that you have generated an OAuth 2.0 Client ID as opposed to a normal API key
According to Google docs for youtube API
- Your application must send an OAuth 2.0 token with any request that accesses private user data

Try uninstalling the app and starting the debug process all over (if you are using the debug.keystore.

Related

Can not connect to Google Game services [duplicate]

I am developing an Android application where I want to use the Google API. For that I have imported the google-play-service-lib project.
I am following this link to initialize GoogleApiClient object.
My code:
1) In the onCreate() method I am building the GoogleApiClient object:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
2) In onStart(), I call mGoogleApiClient.connect().
3) My activity implements
ConnectionCallbacks and OnConnectionFailedListener.
4) My onConnectionFailed() method looks like:
public void onConnectionFailed(ConnectionResult result) {
//in dubug result looks like : ConnectionResult{
//statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent
// {41f8ca70: android.os.BinderProxy#41f8ca10}}
try {
if(!mIntentInProgress && result.hasResolution())
{
mIntentInProgress=true;
result.startResolutionForResult(mActivity, RC_SIGN_IN);
}
} catch (SendIntentException e) {
e.printStackTrace();
}
}
5) My onActivityResult() method contains:
if (requestCode == RC_SIGN_IN) {
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
When I run my app I get a Toast that says that an internal error popped up. I did create the project in the Google console.
I had the same problem.
From documentation:
The client may choose to continue without using the API or it may call startResolutionForResult(Activity, int) to prompt the user to sign in.
So you should try to sign in by using startResolutionForResult() function
#Override
public void onConnectionFailed(ConnectionResult result) {
if (result.hasResolution()) {
try {
// !!!
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
mConnectionResult = result;
}
Just follow google's instructionss
AND CAUTION
Since you are still in development mode, check if you have added your testing email address in the GAME DETAILS center before publishing the game.
Check that you are signing the app with a keystore that is in the apk uploaded to Google Play Developer's Console (if testing, you can upload as alpha and publish while keeping it private).
If not this, it could be other things. Make sure your account's email address is listed in testers in the Account details page (on the settings menu with a gear icon), and the licensed response is set to LICENSED, NOT to RESPOND_NORMALLY
This error indicates that the user needs to authorize your app. There's a full workflow for this, following the tutorial at https://developers.google.com/+/mobile/android/getting-started look for "onConnectionFailed"
Drive api should be enabled from the console page.
Not sure if this is the best answer but it worked for me. I copied onConnectionFailed() from the BasicSamples TakeANumber MainActivity. It calls BaseGameUtils to resolve. Of course that implies you have the BaseGameUtils library included in your project and that's another can of worms. But maybe you can get by with the one method so I copied it below.
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
logger.info( "onConnectionFailed() *play* : attempting to resolve");
if (mResolvingConnectionFailure) {
logger.info( "onConnectionFailed(): already resolving");
return;
}
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
if (!BaseGameUtils.resolveConnectionFailure(this, mGoogleApiClient, connectionResult,
RC_SIGN_IN, getString(R.string.signin_other_error))) {
mResolvingConnectionFailure = false;
}
}
}
From Google BasicSamples BaseGameUtils.java:
public static boolean resolveConnectionFailure(Activity activity,
GoogleApiClient client, ConnectionResult result, int requestCode,
String fallbackErrorMessage) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(activity, requestCode);
return true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
client.connect();
return false;
}
} else {
// not resolvable... so show an error message
int errorCode = result.getErrorCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(errorCode,
activity, requestCode);
if (dialog != null) {
dialog.show();
} else {
// no built-in dialog: show the fallback error message
showAlert(activity, fallbackErrorMessage);
}
return false;
}
}
if you are not using debug keys, push app to google play as alpha, add yourself as a tester and MOST important - follow the "Opt-in" link on Aplha page and CONFIRM that you are the tester.
I'd like to share my experience with this. My case was when using Google Play Services for Google Play Games. I was also getting the onConnectionFailed giving SIGN_IN_REQUIRED error. Finally I realize I had not "Published" my Game settings in the developer console. Not to be mistaken for publishing an "alpha" or "beta" version of your apk. I mean the actual Google Play Games "Game" you create and link to the game's APK.
I had Same problem and solved with this solution ,
I actually had very old version google play-services library so I updated It with latest google play-service library to compile 'com.google.android.gms:play-services:11.0.4' from my previous version library to support your android SDK and maintain compileSDKVersion and targetSDKVersion in gradle:app.
add google drive enabled API_KEY in manifest.and try again
In my case the problem was in sensitive scopes added and not verified:
https://console.developers.google.com/apis/credentials
Credentials -> OAuth consent screen -> Scopes for Google APIs
Make sure you have no unverified scopes.
for my cause i wrongly used release SHA1 key to generate API in developer console.
Then created SHA1 key with debug.keystore and updated in my api credentials.
Its started working.
keytool -list -v -keystore "C:\Users\<user>n\.android\debug.keystore" -alias androiddebugkey -storepass andro
id -keypass android

how to sign in to a google account in my android application without adding that account to the device

I am creating an android application which should have access to a google drive account in order to store and read files in/from google drive. I used google drive android API for this purpose. but the problem is that when the user signs in to the account through the application, the account is also added to the device and the account is accessible through drive, gmail,... applications and I need to restrict the access to that google account to only my application.
Is there anyway to restrict access to google account to just my application?
I show some code related to connecting to google drive below:
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
private boolean mResolvingError = false;
public 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();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//start connection to google play
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
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;
}
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
showMessage("Connected to account");
}
protected void onPause()
{
showMessage("onPause");
super.onPause();
}
protected void onStart() {
super.onStart();
showMessage("onStart");
if (!mResolvingError && !mGoogleApiClient.isConnected()) { // more about this later
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
showMessage("OnStop");
//mGoogleApiClient.disconnect();
super.onStop();
}
protected void onRestart()
{
showMessage("onRestart");
super.onRestart();
if (!mResolvingError && !mGoogleApiClient.isConnected()) { // more about this later
mGoogleApiClient.connect();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
In fact I am making an application which we use to collect data from our users, and therefore we want the data to be stored in a central storage space which both we and other users of application can have access to data.(users have limited access to data through our application). we did the same with dropbox and it works well. but due to some restrictions on accessing dropbox by users, I am looking for alternative solutions. for now I am trying to do the same with google drive.
does anyone have any solution about how should I do this??
in fact the google account has nothing to do with the users of application, it's my google account in which the data coming from application should be stored.
I can't say I fully understand your question, but I'll try to help anyway.
You probably know, that your app needs to be authorized to access the Drive.
Assuming that is working, you need valid gmail account to access the drive. Under normal circumstances, you pull the gmail account from the set of accounts on your device, i.e. myaccount#gmail, youraccount#gmail, .... The list of these accounts is visible in the settings, and you usually add / remove them through the Settings or your app can do it by invoking AccountPicker. I have a little demo here, that handles the issue (follow the MainActivity - REQ_ACCPICK - GDAA branch there). The AccountPicker/Setting either picks an account from the list, or adds a new account to the device.
Now, let's assume you would like to access Drive with a gmail account that is not in the device's list (i.e . NOT-IN-LIST#GMAIL.COM), bypassing account picker, and stick it directly to (see the method here):
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.setAccountName("NOT-IN-LIST#GMAIL.COM")
.build();
If you do this, you'll get 'INVALID ACCOUNT' in 'onConnectionFailed()'. It makes sense, since you've just set an account name not known to the device - effectively even without knowing it's password. I assume that would be a major problem for Google Drive security, right?
So the conclusion (or my best guess) is: Unless you can 'hardcode' the account / passsword info into GoogleApiClient builder, the only way to get the Drive connection is to use one of the 'registered' accounts - they have the correct password already.
UPDATE:
There may be a different way to implement it. Again, UNTESTED. I would try to use a "supervisor" Google account and share the files with users. Android REST Api under DRIVE scope should be able to access these shared files/folders. This way users would access the "supervisor's" files using their own accounts (I vaguely remember hitting 'shared-with-me' files when playing with the REST api). A long shot, but it can easily be tested using the playground - the bottom of the page. And I would even test the same hypothesis under GDAA. I don't know if GDAA can see the 'shared files' under the FILE scope.
Good Luck
I had the same problem and after a lot of research and reading many posts from angry users about this "feature" I am under the impression that this cannot be done using GoogleApiClient.
Instead I used AppAuth to retrieve the authCode / token and then used that token with the Drive REST API to retrieve the users files.
Please note that WebView OAuth is no longer supported by Google as of 4/20/17 which is the reason I suggest AppAuth. AppAuth also works around other unpleasantries such as this.
You can find more details on this approach and a work around for a weird grant error here: invalid_grant trying to get oAuth token from google
Hope this helps.

onConnectionFailed giving SIGN_IN_REQUIRED(4)

I am developing an Android application where I want to use the Google API. For that I have imported the google-play-service-lib project.
I am following this link to initialize GoogleApiClient object.
My code:
1) In the onCreate() method I am building the GoogleApiClient object:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
2) In onStart(), I call mGoogleApiClient.connect().
3) My activity implements
ConnectionCallbacks and OnConnectionFailedListener.
4) My onConnectionFailed() method looks like:
public void onConnectionFailed(ConnectionResult result) {
//in dubug result looks like : ConnectionResult{
//statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent
// {41f8ca70: android.os.BinderProxy#41f8ca10}}
try {
if(!mIntentInProgress && result.hasResolution())
{
mIntentInProgress=true;
result.startResolutionForResult(mActivity, RC_SIGN_IN);
}
} catch (SendIntentException e) {
e.printStackTrace();
}
}
5) My onActivityResult() method contains:
if (requestCode == RC_SIGN_IN) {
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
When I run my app I get a Toast that says that an internal error popped up. I did create the project in the Google console.
I had the same problem.
From documentation:
The client may choose to continue without using the API or it may call startResolutionForResult(Activity, int) to prompt the user to sign in.
So you should try to sign in by using startResolutionForResult() function
#Override
public void onConnectionFailed(ConnectionResult result) {
if (result.hasResolution()) {
try {
// !!!
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
mConnectionResult = result;
}
Just follow google's instructionss
AND CAUTION
Since you are still in development mode, check if you have added your testing email address in the GAME DETAILS center before publishing the game.
Check that you are signing the app with a keystore that is in the apk uploaded to Google Play Developer's Console (if testing, you can upload as alpha and publish while keeping it private).
If not this, it could be other things. Make sure your account's email address is listed in testers in the Account details page (on the settings menu with a gear icon), and the licensed response is set to LICENSED, NOT to RESPOND_NORMALLY
This error indicates that the user needs to authorize your app. There's a full workflow for this, following the tutorial at https://developers.google.com/+/mobile/android/getting-started look for "onConnectionFailed"
Drive api should be enabled from the console page.
Not sure if this is the best answer but it worked for me. I copied onConnectionFailed() from the BasicSamples TakeANumber MainActivity. It calls BaseGameUtils to resolve. Of course that implies you have the BaseGameUtils library included in your project and that's another can of worms. But maybe you can get by with the one method so I copied it below.
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
logger.info( "onConnectionFailed() *play* : attempting to resolve");
if (mResolvingConnectionFailure) {
logger.info( "onConnectionFailed(): already resolving");
return;
}
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
if (!BaseGameUtils.resolveConnectionFailure(this, mGoogleApiClient, connectionResult,
RC_SIGN_IN, getString(R.string.signin_other_error))) {
mResolvingConnectionFailure = false;
}
}
}
From Google BasicSamples BaseGameUtils.java:
public static boolean resolveConnectionFailure(Activity activity,
GoogleApiClient client, ConnectionResult result, int requestCode,
String fallbackErrorMessage) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(activity, requestCode);
return true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
client.connect();
return false;
}
} else {
// not resolvable... so show an error message
int errorCode = result.getErrorCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(errorCode,
activity, requestCode);
if (dialog != null) {
dialog.show();
} else {
// no built-in dialog: show the fallback error message
showAlert(activity, fallbackErrorMessage);
}
return false;
}
}
if you are not using debug keys, push app to google play as alpha, add yourself as a tester and MOST important - follow the "Opt-in" link on Aplha page and CONFIRM that you are the tester.
I'd like to share my experience with this. My case was when using Google Play Services for Google Play Games. I was also getting the onConnectionFailed giving SIGN_IN_REQUIRED error. Finally I realize I had not "Published" my Game settings in the developer console. Not to be mistaken for publishing an "alpha" or "beta" version of your apk. I mean the actual Google Play Games "Game" you create and link to the game's APK.
I had Same problem and solved with this solution ,
I actually had very old version google play-services library so I updated It with latest google play-service library to compile 'com.google.android.gms:play-services:11.0.4' from my previous version library to support your android SDK and maintain compileSDKVersion and targetSDKVersion in gradle:app.
add google drive enabled API_KEY in manifest.and try again
In my case the problem was in sensitive scopes added and not verified:
https://console.developers.google.com/apis/credentials
Credentials -> OAuth consent screen -> Scopes for Google APIs
Make sure you have no unverified scopes.
for my cause i wrongly used release SHA1 key to generate API in developer console.
Then created SHA1 key with debug.keystore and updated in my api credentials.
Its started working.
keytool -list -v -keystore "C:\Users\<user>n\.android\debug.keystore" -alias androiddebugkey -storepass andro
id -keypass android

Error : ConnectionResult{statusCode=INTERNAL_ERROR, resolution=null}

I am developing the application where I am integrating the Google Drive in my App. Below is my code which is I simply copied from the sample code but I am getting exception when connecting with Google Drive.
Exception : ConnectionResult{statusCode=INTERNAL_ERROR, resolution=null} in the onConnectionFailed() method.
Please guys share your views.
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "android-drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = mBitmapToSave;
Drive.DriveApi.newContents(mGoogleApiClient).addResultCallback(new OnNewContentsCallback() {
#Override
public void onNewContents(ContentsResult 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.getContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} 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("image/jpeg").setTitle("Android Photo.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (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(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// Just start the camera again for another photo.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 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 {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
return;
}
saveFileToDrive();
}
#Override
public void onDisconnected() {
Log.i(TAG, "API client disconnected.");
}
}
Heads up! There's a problem in the Developers Console.
If you are getting this bug even after 1) making sure that you have registered the package name with its corresponding certificate fingerprint, and 2) are (re)using an already existing project, then you should check that this project has an product name and an email address (double check that one specially) associated with it, both to be found in the "consent screen" section.
Very old projects may not have these two fields populated. Newer projects have these fields filled out with some default values.
Took me a day to find this...
I resolve this issue by signing my Google Drive application on API console following these steps
Go to the Google Developers Console.
Select a project, or create a new one.
In the sidebar on the left, expand APIs & auth. Next, click APIs.
In the list of APIs, make sure the status is ON for the Drive API.
In the sidebar on the left, select Credentials.
If your application needs to submit authorized requests:
Under OAuth, click Create new Client ID.
Select Installed application and Android.
In the Package name field, enter your Android app's package name.
Paste the SHA1 fingerprint into the form where requested.
Click Create Client ID.
I solved the issue from register the application and generate signing certificate fingerprint.
https://developers.google.com/drive/android/auth#generate_the_signing_certificate_fingerprint_and_register_your_application
I followed above links and It solved my problem.
For me the problem was that when in the example there was :
.addApi(Drive.API)
And I didn't added the drive api in the console
this error message helped me to figure out the issue
com.google.android.gms.drive.auth.c: Authorization failed: server
returned error: Access Not Configured. The API is not enabled for your
project, or there is a per-IP or per-Referer restriction configured on
your API key and the request does not match these restrictions. Please
use the Google Developers Console to update your configuration.. See
https://developers.google.com/drive/handle-errors for details.
Don't forget the permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Do you have any error messages in logcat? The most likely cause of a failed connection is that you haven't properly setup an app in the cloud console.
See the instructions here: https://developers.google.com/drive/android/auth
In my case, I had to change the Client ID to use the exact package name of the activity class building the GoogleApiClient object, not a higher-level package.
I was also getting the same error.
For my project, Drive API was not enabled under API & auth -> APIs.
After enabling this Drive API, this problem was resolved.
I solved adding this line to gradle:
compile 'com.google.android.gms:play-services-identity:8.1.0'
You need to have two separate Client IDs, one for debug, the other one for release.
Sometimes we miss the obvious.
In Android Studio go to
Tool-> Android-SDK Manager -> Google Play Service
Update the Google Play Service..I am sure it will work
I got the same problem as above, when I moved an existing application from Eclipse to Android studio. My problem was that I named applicationId different from the package id. Changing applicationId to be the same as the package name solved the problem.
I got the same issue. My sign-in was working but it stopped working all of sudden. I tried all the solutions mentioned here. But didn't solve my problem. However, upon disabling the google sign in and enabling it solved my problem. So just go to the firebase console, select Authentication > Sign-in Methods > google > click Edit > disable and enable.

Android: Login using google account?

I am trying to find a good documented example of how to perform a login in my app using a google account.
Maybe I am looking in the wrong place, but i can't find anything in the android sdk docs. From what i understand its part of Google Services but still having problems find examples.
I also need to support if the user has more than 1 google account configured on the device to popup and ask which account to use.
Then on future loading of my app I would automatically login.
Can anyone point me in the right direction, or are there no examples available?
Thanks
You probably want to use this guide:
https://developers.google.com/+/mobile/android/sign-in
From the guide:
You must create a Google APIs Console project and initialize the PlusClient object.
Add the Google+ Sign-In button to your app
Add the SignInButton in your application's layout:
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Initialize mPlusClient with the requested visible activities in your Activity.onCreate handler.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
.build();
}
In the Android activity, register your button's OnClickListener to sign in the user when clicked:
findViewById(R.id.sign_in_button).setOnClickListener(this);
After the user has clicked the sign-in button, you should start to resolve any connection errors held in mConnectionResult. Possible connection errors include prompting the user to select an account, and granting access to your app.
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
When the user has successfully signed in, your onConnected handler will be called. At this point, you are able to retrieve the user’s account name or make authenticated requests.
#Override
public void onConnected(Bundle connectionHint) {
mConnectionProgressDialog.dismiss();
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}

Categories

Resources