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??
Related
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.
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 have followed the following tutorials to integrate Google+ in the android app.
https://developers.google.com/+/mobile/android/sign-in#add_the_google_sign-in_button_to_your_app
http://www.riskcompletefailure.com/2013/03/common-problems-with-google-sign-in-on.html
http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
I am able to sign in into Google account, and am able to retrieve the information also. Thing is I am not able to log out.
I am logging in G+ in Login activity and storing the session using Shared Preferences, and closing the session in another Base activity, passing the boolean value to the Login activity regarding the closing of the session. Though the Session is not active or user has not logged in, login activity automatically connects to the G+ whenever login activity is started. Tried to do logic on onConnected but to no avail.
Below is my code snippet.
public class LoginActivity extends BaseActionBar implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private Button btnLogin, btnFgetPwrd, btnRegister;
// Logcat tag
private static final String TAG = "LoginActivity";
// Google Plus
private static final int GOOGLE_SIGN_IN = 0;
// Google Plus Profile Data
String GpersonName, GpersonPhotoUrl, Gemail, googleError, GCustId;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
private SignInButton btnGooglePlus;
// A flag indicating that a PendingIntent is in progress and prevents us
// from starting further intents.
private boolean mIntentInProgress;
// Track whether the sign-in button has been clicked so that we know to
// resolve all issues preventing sign-in without waiting.
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
// Session Manager Class
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Initializing google plus api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
// Session Manager
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn() == false) {
Log.v(TAG, "false");
mSignInClicked = false;
DataStore.LoginGoogle = false;
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
} else {
Intent i = new Intent(LoginActivity.this, UserProfileActivity.class);
startActivity(i);
}
btnLogin.setOnClickListener(this);
btnFgetPwrd.setOnClickListener(this);
btnRegister.setOnClickListener(this);
btnGooglePlus.setOnClickListener(this);
}
// Facebook and Google Plus
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == GOOGLE_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
} else if (requestCode == FB_SIGN_IN) {
Session.getActiveSession().onActivityResult(this, requestCode,
responseCode, intent);
}
}
// Google Plus
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.loginBtn:
// Login Button Clicked
break;
case R.id.loginBtnFrgtPass:
// Forgot Button Clicked
i = new Intent(LoginActivity.this, ForgotPasswordActivity.class);
startActivity(i);
break;
case R.id.loginBtnRegis:
// Register Button Clicked
i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
break;
case R.id.loginBtn_sign_in:
signInWithGplus();
break;
}
}
// Sign-in into google
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
// Method to resolve any sign-in errors
private void resolveSignInError() {
Log.v(TAG, mConnectionResult.toString());
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution()
.getIntentSender(), GOOGLE_SIGN_IN, null, 0, 0, 0);
// mConnectionResult
// .startResolutionForResult(this, GOOGLE_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
// Google+ connection
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Log.v(TAG, "onConnected");
mSignInClicked = false;
Toast.makeText(this, "User is connected to Google+", Toast.LENGTH_LONG)
.show();
btnLogin.setEnabled(false);
// Get user's information
getProfileInformation();
}
// Google+ connection
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
// Google+ connection
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
Log.v(TAG, result.toString());
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
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();
}
}
} // Normal Logging in
}
Code snippet of the logging out of session from base activity
if (session.isLoggedIn()) {
session.logoutUser();
DataStore.LoginGoogle = false;
setOptionTitle(R.id.action_login, "Login");
}
import com.google.android.gms.auth.api.Auth;
Auth.GoogleSignInApi.signOut(googleApiClient);
Signs out the current signed-in user if any. It also clears the account previously selected by the user and a future sign in attempt will require the user pick an account again.
https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInApi
NOTE - googleApiClient object should be in the connected state to sign out the user.
I found the solution.
After referring following sites, I found the solutions.
Android implementing Google plus login error on mConnectionResult.hasResolution()
http://www.riskcompletefailure.com/2013/03/common-problems-with-google-sign-in-on.html
I had to check the logging session in onConnected, and do the log out process.
Below is the code snippet.
// Google+ connection
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Log.v(TAG, "onConnected");
if (ShopRunDataStore.LoginGoogle) {
Log.v(TAG, "Google logged in");
mSignInClicked = false;
Toast.makeText(this, "User is connected to Google+",
Toast.LENGTH_LONG).show();
btnfacebook.setEnabled(false);
btnLogin.setEnabled(false);
// Get user's information
getProfileInformation();
} else {
Log.v(TAG, "In if condition to log off");
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
// mGoogleApiClient.connect();
mSignInClicked = false;
btnGooglePlus.setEnabled(true);
btnfacebook.setEnabled(false);
btnLogin.setEnabled(true);
}
}
}
If you have read carefully the documentation from the link you provided, you would have seen that there is a sample function on how to log out the use
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_out_button) {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
}
https://developers.google.com/+/mobile/android/sign-in#add_the_google_sign-in_button_to_your_app
Under "Sign out the user"
The problem with my code was that the re-login was happening before the disconnect would complete. The solution was to begin the re-login only after the disconnect would be complete i.e. in the OnConnected listener.
I am trying to implement Google+ authentication in my Android application. In order to do this, I have followed this Google tutorial.
When the permission dialog appears, if the user clicks SIGN IN, everything works fine. However, if he clicks CANCEL, the dialog closes for a couple of seconds and then shows back up. This goes on forever so there's no way to properly cancel the operation. Why is this happening?
This is the relevant code, adapted from the tutorial:
/* 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;
/* Track whether the sign-in button has been clicked so that we know to resolve
* all issues preventing sign-in without waiting.
*/
private boolean mSignInClicked;
/* Store the connection result from onConnectionFailed callbacks so that we can
* resolve them when the user clicks sign-in.
*/
private ConnectionResult mConnectionResult;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress;
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/* A helper method to resolve the current ConnectionResult error. */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution().getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} 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();
}
}
}
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();
}
}
}
// Login by email button click listener.
public class ButtonLoginGPlusClicked implements View.OnClickListener {
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
// Save credentials.
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
SharedPreferencesHelper.updateStringValue(
LoginAsVerifiedTracker.this,
R.string.preferences_user_id,
currentPerson.getId());
SharedPreferencesHelper.updateStringValue(
LoginAsVerifiedTracker.this,
R.string.preferences_user_name,
currentPerson.getDisplayName());
// Close.
setResult(Activity.RESULT_OK);
finish();
return;
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
EDIT:
Here the onActivityResult class:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_SIGN_IN: {
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
break;
}
case 1: {
overridePendingTransition(R.anim.slide_right_to_left_enter,
R.anim.slide_right_to_left_exit);
break;
}
}
}
This is the dialog I'm talking about:
Per step 5 of the Google+ Sign In guide:
You should then reset the state of the flags when control returns to your Activity in onActivityResult.
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();
}
}
}
Note the check against responseCode - only when the user has hit the sign in button is responseCode equal to RESULT_OK. This ensures that the cancel button stops the resolveSignInError() call in onConnectionFailed() (which is what causes it to loop forever).
I have tried a lot but not able to customize the Google plus Signin Button.
Please help me.
Thanks
First, at the layout.xml add your button:
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
At the application activity, register to this button a onclicklistener :
findViewById(R.id.sign_in_button).setOnClickListener(this);
And also use this code that say to the app wait to the sign in button:
/* Track whether the sign-in button has been clicked so that we know to resolve
* all issues preventing sign-in without waiting.
*/
private boolean mSignInClicked;
/* Store the connection result from onConnectionFailed callbacks so that we can
* resolve them when the user clicks sign-in.
*/
private ConnectionResult mConnectionResult;
/* A helper method to resolve the current ConnectionResult error. */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} 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();
}
}
}
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();
}
}
}
And use this onclick code (indicates if it is the sign in button) :
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInErrors();
}
}
Use this code to indicate if you are already signed in:
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();
}
}
}
And add a message when you signed in successfully:
#Override
public void onConnected(Bundle connectionHint) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}
Also, Read this:
https://developers.google.com/+/mobile/android/sign-in