I am trying to connect my App to Google Play Services, for to add games achievements, but it doesn´t connect. It returns me this message:
Failed to sign in. Please check your network connection and try again.
I reinstalled Google Services, and it didn´t fix the problem.
Here is my code.
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
{
public static GoogleApiClient googleApiClient;
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
}
#Override
protected void onStart() {
try
{
super.onStart();
googleApiClient.connect();
}catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onStop() {
try
{
super.onStop();
googleApiClient.disconnect();
}catch (Exception e)
{
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode,Intent intent)
{
if (requestCode == RC_SIGN_IN)
{
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (resultCode == RESULT_OK)
{
googleApiClient.connect();
}
else
{
BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.error_conectar_google_juegos2);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("STATE_RESOLVING_ERROR", false);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
if (mResolvingConnectionFailure)
{
return;
}
if (mSignInClicked || mAutoStartSignInflow)
{
mAutoStartSignInflow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
if (!BaseGameUtils.resolveConnectionFailure(this,googleApiClient, connectionResult,RC_SIGN_IN, R.string.error_conectar_google_juegos1))
{
mResolvingConnectionFailure = false;
}
}
}
}
The execution flow is the next:
onCreate()
onStart()
onConnectionFailed()
onSaveinstanceState()
It asks for my Google Account
onActivityResult()
Here it goes to the "ELSE" of the onActivityResult().
When it fails, it shows the message I said before.
I have good internet connection on my device, and I use Android Games of Google Games with no problem. What can be happening?
Thank you so much.
Related
I am new to android programming and I am trying to use google play service. I am following this guide step by step.
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;
private GoogleApiClient mGoogleApiClient;
boolean mExplicitSignOut = false;
boolean mInSignInFlow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Google Api Client with access to the Play Games services
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
// add other APIs and scopes here as needed
.build();
...
...
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle connectionHint) {
// The player is signed in. Hide the sign-in button and allow the
// player to proceed.
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingConnectionFailure) {
// already resolving
return;
}
// if the sign-in button was clicked or if auto sign-in is enabled,
// launch the sign-in flow
if (mSignInClicked || mAutoStartSignInflow) {
mAutoStartSignInflow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
// Attempt to resolve the connection failure using BaseGameUtils.
// The R.string.signin_other_error value should reference a generic
// error string in your strings.xml file, such as "There was
// an issue with sign-in, please try again later."
if (!BaseGameUtils.resolveConnectionFailure(this,
mGoogleApiClient, connectionResult,
RC_SIGN_IN, R.string.signin_other_error)) {
mResolvingConnectionFailure = false;
}
}
// Put code here to display the sign-in button
}
#Override
public void onConnectionSuspended(int i) {
// Attempt to reconnect
mGoogleApiClient.connect();
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (resultCode == RESULT_OK) {
mGoogleApiClient.connect();
} else {
// Bring up an error dialog to alert the user that sign-in
// failed. The R.string.signin_failure should reference an error
// string in your strings.xml file that tells the user they
// could not be signed in, such as "Unable to sign in."
BaseGameUtils.showActivityResultError(this,
requestCode, resultCode, R.string.signin_failure);
}
}
}
// Call when the sign-in button is clicked
public void signInClicked(View v) {
mSignInClicked = true;
mGoogleApiClient.connect();
}
// Call when the sign-out button is clicked
public void signOutclicked(View v) {
mSignInClicked = false;
Games.signOut(mGoogleApiClient);
}
Then, in the app start The google play connection window pops up
but then it shows network error. Although I have wifi connection. Log doesn't show any problem and I don't know where to start looking for the problem.
Could you give me some advice??
Can't connect to the google api, the result on the monitor is:
E/GoogleFit: RESULT_CANCELED (this message only appears after select the google account)
Obviously, i have the internet permission on my app.
on the google developer console, the name of the package is the same of my project.
Here is the code:
public class MainActivity extends AppCompatActivity implements OnDataPointListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private static final int REQUEST_OAUTH = 1;
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;
private GoogleApiClient mApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
}
mApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this).addOnConnectionFailedListener(this)
.build(); {
}
}
#Override
protected void onStart() {
super.onStart();
mApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
DataSourcesRequest dataSourcesRequest = new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build();
ResultCallback<DataSourcesResult> dataSourcesResultResultCallback = new ResultCallback<DataSourcesResult>() {
#Override
public void onResult(#NonNull DataSourcesResult dataSourcesResult) {
for(DataSource dataSource : dataSourcesResult.getDataSources()){
if(DataType.TYPE_STEP_COUNT_CUMULATIVE.equals(dataSource.getDataType())){
registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_CUMULATIVE);
}
}
}
};
Fitness.SensorsApi.findDataSources(mApiClient, dataSourcesRequest).setResultCallback(dataSourcesResultResultCallback);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if(!authInProgress){
try{
authInProgress = true;
connectionResult.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
}catch (IntentSender.SendIntentException e){
}
}else{
Log.e("GoogleFit", "AuthInProgress");
}
}
#Override
public void onDataPoint(DataPoint dataPoint) {
for(final Field field: dataPoint.getDataType().getFields()){
final Value value = dataPoint.getValue(field);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Field"+field.getName()+"Value:"+ value,Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_OAUTH){
authInProgress = false;
if(resultCode == RESULT_OK){
if(!mApiClient.isConnecting() && !mApiClient.isConnected()){
mApiClient.connect();
}
}else if(resultCode == RESULT_CANCELED){
Log.e("GoogleFit", "RESULT_CANCELED");
}
}else {
Log.e("GoogleFit", "requestCode NOT request_oauth");
}
super.onActivityResult(requestCode, resultCode, data);
}
private void registerFitnessDataListener(DataSource dataSource, DataType dataType){
SensorRequest request = new SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(dataType)
.setSamplingRate(3, TimeUnit.SECONDS)
.build();
Fitness.SensorsApi.add(mApiClient, request, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if(status.isSuccess()){
Log.e("GoogleFit", "SensorApi succesfully added");
}
}
});
}
#Override
protected void onStop() {
super.onStop();
Fitness.SensorsApi.remove(mApiClient, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if(status.isSuccess()){
mApiClient.disconnect();
}
}
});
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putBoolean(AUTH_PENDING, authInProgress);
}
}
Fixed problem:
Well, i've made some investigations and I found a solution.
The code is working good, the problem was on the OAuthClient.
Steps to avoid the problem:
Step 1:
Go to Google development console and enable the API (Fitness API in my case),it's very important i this step, to make ensure that you create the OAuth credentials, just use the command given and write the SHA1
Step 2:
Go to Firebase Console and follow the steps
Step 3:
Download the JSON and put in your app folder (in your project)
Step 4:
Create a metadata like this in the manifest:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="-key of your JSON-" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Hope it helps for the others! this solution worked for me!
Make sure that you are using the correct OAuth 2.0 Client ID code. This may lead to an error if you're using it wrong. Also make sure that you have updated the authentication flow based from the latest documentation for Google Sign-In.
You may refer with these SO threads: Google Oauth 2.0 RESULT_CANCELED while using Google Fit api and GoogleApiClient not connecting while using google fit.
Hi I use Google login in my app it works fine but whenever I logging out I tried many solution for logging out but it doesn't works for me and if I further clicks on Google login button then app crashes.
Here is my code for Login
public class LoginActivity extends Activity implements AsyncInterface,
OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
EditText etLoginEmail, etLoginPassword;
Button btnLoginSubmit, btnLoginSignup;
TextView txtLoginForgotPass;
LoginResponseMain loginResponseMain;
/* For Google */
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
// Google Sign In Button
btnSignIn.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (AppMethod.getBooleanPreference(LoginActivity.this, AppConstant.PREF_FIRST_LOGIN)) {
//startActivity(new Intent(LoginActivity.this, HomePage.class));
} else {
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public void init() {
loginResponseMain = new LoginResponseMain();
btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
}
#Override
public void onWSResponse(String json, String WSType) {
if (WSType == AppConstant.WS_LOGIN_G) {
try {
Log.e("Json", json);
JSONObject jobj = new JSONObject(json);
boolean error = jobj.getBoolean("error");
if (!error) {
JSONArray jsonArray = jobj.getJSONArray("user");
JSONObject jobjUser = jsonArray.getJSONObject(0);
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_FACEBOOK_ID, jobjUser.getString("facebook_id"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_GOOGLE_ID, jobjUser.getString("google_plus_id"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_EMAIL, jobjUser.getString("email"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_FNAME, jobjUser.getString("first_name"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_LNAME, jobjUser.getString("last_name"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_UPDATED_AT, jobjUser.getString("updated_at"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_CREATED_AT, jobjUser.getString("created_at"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_ID, String.valueOf(jobjUser.getInt("id")));
Intent i = new Intent(LoginActivity.this, TermsForUseActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(LoginActivity.this, AppConstant.SOMETHING_WRONG_TRY_AGAIN, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
getProfileInformation();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
// Login Button Click
case R.id.sign_in_button:
signInWithGplus();
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result2 = googleAPI.isGooglePlayServicesAvailable(this);
if (result2 != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result2)) {
googleAPI.getErrorDialog(this, result2, 0).show();
}
}
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult; // Store the ConnectionResult for later usage
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to resolve all errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
/* Fetching user's information name, email, profile pic */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
String url = AppConstant.LOGIN_WITH_G;
// WS for google login data submit.
if (AppMethod.isNetworkConnected(LoginActivity.this)) {
String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String device_token = AppMethod.registerForGCM(LoginActivity.this);
Uri.Builder values = new Uri.Builder()
.appendQueryParameter("first_name", personName)
.appendQueryParameter("email", email)
.appendQueryParameter("udid", android_id)
.appendQueryParameter("login_type", "0")
.appendQueryParameter("device_token", device_token)
.appendQueryParameter("google_plus_id", currentPerson.getId());
WsHttpPostWithNamePair wsHttpPost = new WsHttpPostWithNamePair(LoginActivity.this, AppConstant.WS_LOGIN_G, values);
wsHttpPost.execute(url);
} else {
Toast.makeText(LoginActivity.this, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
Now i need to signout from another activity use this code
For Logging out
public class HomePage extends TabActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult> {
DrawerLayout dLayout;
LinearLayout right_layout;
Button btnViewProfile, btnLogout;
//Google
GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private ConnectionResult mConnectionResult;
private static final int RC_SIGN_IN = 0;
private boolean mSignInClicked;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.home_page);
llHomePageMain = (LinearLayout) findViewById(R.id.llHomePageMain);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
mGoogleApiClient.connect();
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
right_layout = (LinearLayout) findViewById(R.id.right_layout);
btnViewProfile = (Button) findViewById(R.id.btnViewProfile);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnViewProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Right Layout", "Profile");
dLayout.closeDrawer(Gravity.END);
Intent i = new Intent(HomePage.this, ProfileActivity.class);
startActivity(i);
}
});
btnLogout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AppMethod.clearApplicationData(HomePage.this);
googlePlusLogout();
loginSessionClear();
}
}
});
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
}
private void resolveSignInError() {
if (mConnectionResult != null)
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
private void googlePlusLogout() {
if (mGoogleApiClient != null)
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result2 = googleAPI.isGooglePlayServicesAvailable(this);
if (result2 != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result2)) {
googleAPI.getErrorDialog(this, result2, 0).show();
}
}
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult;
if (mSignInClicked) {
resolveSignInError();
}
}
}
#Override
public void onBackPressed() {
dLayout.closeDrawers();
super.onBackPressed();
}
public void loginSessionClear() {
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_EMAIL, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_FNAME, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_LNAME, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_UDID, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_DEVICE_TOKEN, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_UPDATED_AT, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_CREATED_AT, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_GOOGLE_ID, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_ID, String.valueOf(""));
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onResult(People.LoadPeopleResult loadPeopleResult) {
}
}
This method doesnt work for me.
Even if i clear preference and try for new login with google then app crashes.
Logcat Error
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.common.ConnectionResult.hasResolution()' on a null object reference
Check null first
private void resolveSignInError() {
if (mConnectionResult != null)
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
and call bellow method for Logout
private void googlePlusLogout() {
if (mGoogleApiClient != null)
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
I'm trying to implement Google+ login in my application but it won't work.
Everytime I click log in, the onConnectionFailed gets called as soon as I choose the account.
Could someone please let me know what's wrong?
public class LoginActivity extends ActionBarActivity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener{
/*
Variables
*/
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress;
/*
* True if the sign-in button was clicked. When true, we know to resolve all
* issues preventing sign-in without waiting.
*/
private boolean mSignInClicked;
/*
Lifecycle
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
// Sign in button click listener
findViewById(R.id.googleSignInButton).setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/*
Callbacks
*/
#Override
public void onClick(View v) {
if (v.getId() == R.id.googleSignInButton && !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
mGoogleApiClient.connect();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i("TAG", "onConnectionFailed");
if (!mIntentInProgress) {
if (mSignInClicked && connectionResult.hasResolution()) {
// The user has already clicked 'sign-in' so we attempt to resolve all
// errors until the user is signed in, or they cancel.
try {
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
mIntentInProgress = 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.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i("TAG", "onConnected");
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
Log.i("TAG", "onConnectionSuspended");
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.reconnect();
}
}
}
}
I even downloaded official Google sample for login and I get the same error. It just won't log in and connect.
I have good connection (even wifi) and I tried it on multiple phones.
It just might be an issue with the key you are using.
Go to your google api's console Try Generating a new Cient id with your
SHA1 obtained from debug.keystore and try Login again.I'm sure it'll help solve your issue.
I am integrating google plus in my application from this URL https://developers.google.com/+/mobile/android/sign-in but i am not able to get chooser of google plus account to login and in ConnectionResult i always get ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{4223c668: android.os.BinderProxy#4224b9c0}}...
I tried lots of links and created and deleted client id its not working for me
Here is my Code
#Override
protected void onCreate(Bundle savedInstanceState) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
btnGooglePlus = (SignInButton) findViewById(R.id.sign_in_button);
btnGooglePlus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
// Store the ConnectionResult so that we can use it later when the
// user clicks
// 'sign-in'.
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
/* A helper method to resolve the current ConnectionResult error. */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
// The intent was canceled before it was sent. Return to the
// default
// state and attempt to connect to get an updated
// ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
You don't do anything in your OnClickListener.
You need to call resolveSignInError() from onClick, which will recognize the SIGN_IN_REQUIRED and start the login flow accordingly.