Android Google+ issues - android

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.

Related

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.

Logging Out from the Google Plus integrated in the android Application

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.

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+ integration. Calling connect() while still connected, missing disconnect()

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

Categories

Resources