Android: Google+ integration. Calling connect() while still connected, missing disconnect() - android

I am working on app which is having Google+ integration in android app, I have tried to login with Google+ account, now PlusClient can not connect with account, what I did so far.
PlusClient mPlusClient;
mPlusClient.connect();
When I have checked that mPlusClient is connected or not, I got below resilt.
Log.i("PlusClient", ""+mPlusClient.isConnected());
Output is **False**.
Any help would be appreciated.

Hope its helpful to you..this blog describe Google+ integration nicely
http://ankitthakkar90.blogspot.in/

Read this before start: https://developers.google.com/+/mobile/android/getting-started
And then this: https://developers.google.com/+/mobile/android/sign-in
You need to initialize:
Initialize the PlusClient object in your Activity.onCreate handler.
Invoke PlusClient.connect during Activity.onStart() .
Invoke PlusClient.disconnect during Activity.onStop() .
Your activity will listen for when the connection has established or failed by implementing the ConnectionCallbacks and OnConnectionFailedListener interfaces.
When the PlusClient object is unable to establish a connection, your implementation has an opportunity to recover inside your implementation of onConnectionFailed, where you are passed a connection status that can be used to resolve any connection failures. You should save this connection status in a member variable and invoke it by calling ConnectionResult.startResolutionForResult when the user presses the sign-in button or +1 button.
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this,REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the intent so that we can start an activity when the user clicks
// the sign-in button.
mConnectionResult = result;
}
#Override
public void onConnected() {
// We've resolved any connection errors.
mConnectionProgressDialog.dismiss();
}
Because the resolution for the connection failure was started with startActivityForResult and the code REQUEST_CODE_RESOLVE_ERR, we can capture the result inside Activity.onActivityResult.
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
And example would be:
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.*;
import com.google.android.gms.plus.PlusClient;
public class ExampleActivity extends Activity implements View.OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "ExampleActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create an plusclient object
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity", " http://schemas.google.com/BuyActivity")
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
}
#Override
protected void onStart() {
super.onStart();
//connect
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
//disconnect
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (result.hasResolution()) {
try {
//start Solution for connectivity problems
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
//Try connect again
mPlusClient.connect();
}
}
#Override
public void onConnected() {
//Get account name
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
}
You can also add a button in xml to sign in and set a listener in class with findViewById(R.id.sign_in_button).setOnClickListener(this);
:
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Related

Android - Connecting to Google Play Service API

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??

Google Play Services unavailable when trying to Log In with Google+

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.

Android Play Services Login: Google Plus cancel button is not working properly

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).

Android Login with Google Plus

I've been following this tutorial.
http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
But when I'm tested the app through the real device,
When I click on the Sign in button, a toast is appeared saying "An internal error has occurred"
Could you please help me with this.
Thanks in advance.
Usually 'Internal error' shows up if one of the following is wrong:
In Google's Developer console website:
You have created a project, but not enabled Google api
Inside the Project:
Credentials
SHA1 Code is not correct
Package Name is not correct
Consent Screen
The associated email address is missing
Product Name is missing
If all these are correct, it should work automatically....
Try below code:
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private static final int REQUEST_CODE_SHARE = 1000;
private PlusClient mPlusClient;
private PlusClient.Builder mPlusClientBuilder;
private PlusShare.Builder mPlusShareBuilder;
// In your onCreate()
mPlusClientBuilder = new Builder(this, this, this);
mPlusClientBuilder.setScopes(Scopes.PLUS_LOGIN, Scopes.PROFILE);
mPlusClient = mPlusClientBuilder.build();
mPlusClient.connect();
// Overrides methods
#Override
public void onConnectionFailed(ConnectionResult result) {
if (result.hasResolution()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.disconnect();
mPlusClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
String accountName = mPlusClient.getAccountName();
btnSignIn.setText(getString(R.string.signout));
textUserName.setText(accountName);
}
// Signin Click event
btnSignIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!mPlusClient.isConnected() && btnSignIn.getText().equals(getString(R.string.signin))) {
mPlusClient.connect();
} else if (mPlusClient.isConnected() && btnSignIn.getText().equals(getString(R.string.signout))) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
btnSignIn.setText(getString(R.string.signin));
textUserName.setText("");
txtLoginAs.setVisibility(View.GONE);
}
}
});
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mPlusClient.disconnect();
mPlusClient.connect();
} else if (requestCode == REQUEST_CODE_SHARE && responseCode == RESULT_OK) {
finish();
}
}

Android Google+ issues

I want to do the post on google-plus through my app. I am using this code for that but it not working it giving me message that I couldn't post the message and I also having a doubt where i will use my clientId?.please help me.
public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "ExampleActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private Button shareButton=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shareButton=(Button)findViewById(R.id.share_button);
shareButton.setOnClickListener(this);
mPlusClient = new PlusClient.Builder(this, this, this)
.setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
.setScopes(Scopes.PLUS_LOGIN) // recommended login scope for social features
// .setScopes("profile") // alternative basic login scope
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.share_button:
Intent shareIntent = new PlusShare.Builder(this)
.setType("text/plain")
.setText("Welcome to the Google+ platform.")
.setContentUrl(Uri.parse("https://developers.google.com/+/"))
.getIntent();
startActivityForResult(shareIntent, 0);
break;
}
}
}
Thanks in advance
You don't need a client ID anywhere in the app - its inferred from the app packagename and the SHA1 of the signing key (which is why it asks for those in the API console). However, you don't need sign in or a key at all to do the kind of basic sharing you're doing. To test, you might want to remove all PlusClient/sign in related code until you're comfortable the PlusShare builder is creating the intent properly.
Could you make sure you're using the latest version of Google Play services (4.1) and see if you have any issues still? If so, could you check whether any more error details appear in logcat.

Categories

Resources