Infinite loop when attemping to check if user is signed in. google + - android

I am attempting to check if the user is signed in and weather or not they are, send them to the login or keep them on the main activity.
Main Activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
public class MainActivity extends Activity {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Plus.API, null).addScope(Plus.SCOPE_PLUS_LOGIN).build();
if (!mGoogleApiClient.isConnected()) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
LoginActivity
package com.alfalfa.thisthat;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
public class LoginActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, OnClickListener {
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private static SignInButton mSignInButton;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
mSignInButton.setOnClickListener(this);
mSignInButton.setEnabled(true);
mSignInButton.setSize(SignInButton.SIZE_WIDE);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
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 onClick(View view) {
if (view.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInErrors();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
mConnectionResult = result;
if (mSignInClicked) {
resolveSignInErrors();
}
}
}
private void resolveSignInErrors() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
mSignInClicked = false;
navigateToMainActivity();
Toast.makeText(this, "User is connected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
public void navigateToMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
When I start the app, it loads into the login screen. When I click the sign in button, the app backs in and our of the LoginActivity infinitely.

I removed a piece of code from my app that does something similar. It is Google Drive related, but easy to adapt.
On menu selection, it pops-up account picker and connects to GAC with the selected account.
Checking if the user is signed-in is irrelevant in my situation. If there has been a valid user connected before, the connect() is successful, otherwise the account picker pops-up. There is more about it in SO 21610239. And I believe there is no way to get current signed user, unless you pop-up the account picker and get it from the return (KEY_ACCOUNT_NAME below).
public class SomeActivity extends Activity
implements ConnectionCallbacks, OnConnectionFailedListener {
GoogleApiClient mGAC;
// from menu: user pops up account picker and selects account
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.acc_select:
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false, null, null, null, null);
startActivityForResult(intent, AUTH_REQUEST);
return true;
}
return super.onOptionsItemSelected(item);
}
// back from account picker (invoked from menu OR from onConnectionFailed())
#Override protected void onActivityResult(final int rqst, final int rslt, final Intent it) {
switch (rqst) {
case AUTH_REQUEST:
if (mGAC == null) {
mGAC = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.setAccountName(it.getStringExtra(AccountManager.KEY_ACCOUNT_NAME))
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
if ((mGAC != null) && !mGAC.isConnected())
mGAC.connect();
break;
}
}
// connection failed, either fatal, or needs account / authorization
#Override public void onConnectionFailed(ConnectionResult rslt) {
if (!rslt.hasResolution()) { // FATAL ------->>>>
Toast.makeText(this, "FAILED", Toast.LENGTH_LONG).show();
} else try { // needs authorization
rslt.startResolutionForResult(this, AUTH_REQUEST);
} catch (SendIntentException e) {}
}
#Override public void onConnected(Bundle connectionHint) {
// do my stuff here
}
#Override public void onConnectionSuspended(int i) {}
}

There's one glaring issue I see in the code you posted:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Plus.API, null).addScope(Plus.SCOPE_PLUS_LOGIN).build();
if (!mGoogleApiClient.isConnected()) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
At this point mGoogleApiClient will never be connected. To determine if the user isn't successfully connected (there are a number of reasons this could happen), you want to add an OnConnectionFailedListener to the Builder, then call .connect() on mGoogleApiClient and wait for OnConnectionFailedListener#onConnectionFailed() to be called. If that happens, then redirect the user back to the login Activity.

Related

How can I keep my google plus session opened after android application close?

this is my first time posting here because I've never had the need before because every question I had was already answered!
The thing is that I'm trying to log in my android application with google plus but if I close my application.. I don't know how to see if the user was already signed in.. Is there any way to do check it?
For example:
- You login in my application and then you go to the MainActivity instead of the login activity.
- Then you don't log out, you simply close my app for.. maybe half an hour..
- After that.. you open my app again and instead go to the MainActivity again.. you are in the login activity again..
Is there any way to know if you were already signed in?
This is my login class:
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
public final class LoginGPlusFragment extends Fragment implements
View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
{
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/**
* True if we are in the process of resolving a ConnectionResult
*/
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;
static GoogleApiClient mGoogleApiClient;
SignInButton btnLogin;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_gplus_login, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
Log.d("DEBUG","onViewCreated LoginGPlusFragment");
super.onViewCreated(view, savedInstanceState);
if(mGoogleApiClient == null || !mGoogleApiClient.isConnected())
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope("profile"))
.build();
else
Log.d("DEBUG","onViewCreated you're already connected");
btnLogin = (SignInButton)view.findViewById(R.id.sign_in_button);
btnLogin.setOnClickListener(this);
}
#Override
public void onConnectionFailed(ConnectionResult result)
{
Log.d("DEBUG","onConnectionFailed LoginGPlusFragment");
if (!mIntentInProgress)
{
if (mSignInClicked && result.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
{
result.startResolutionForResult(getActivity(), 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 onClick(View view)
{
if (view.getId() == R.id.sign_in_button && !mGoogleApiClient.isConnecting())
{
mSignInClicked = true;
mGoogleApiClient.connect();
}
}
#Override
public void onResume()
{
super.onResume();
Log.d("DEBUG","onResume LoginGPlusFragment");
if(mGoogleApiClient!=null && mGoogleApiClient.isConnected())
launchChatActivity();
else
Log.d("DEBUG","onResume you are disconnected");
}
#Override
public void onConnected(Bundle bundle)
{
Log.d("DEBUG","onConnected LoginGPlusFragment");
mSignInClicked = false;
launchChatActivity();
}
private void launchChatActivity()
{
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.d("DEBUG", "Connected with google. You are "+accountName);
btnLogin.setVisibility(View.INVISIBLE);
Intent i = new Intent(getActivity(), ChatActivity.class);
startActivity(i);
getActivity().finish();
}
#Override
public void onConnectionSuspended(int i)
{
Log.d("DEBUG","onConnectionSuspended LoginGPlusFragment");
mGoogleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
Log.d("DEBUG","onActivityResult LoginGPlusFragment");
if (requestCode == RC_SIGN_IN)
{
if (responseCode != getActivity().RESULT_OK)
{
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnected())
{
mGoogleApiClient.reconnect();
}
}
}
}
Thank you very much!!
Ok, I will answer myself.
As I still don't know if there is a way to do it automatically, I do it at the moment by saving a shared preference in the onConnected method:
#Override
public void onConnected(Bundle bundle)
{
SharedPreferences sharedPref = getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("signed_in_with_google", true);
editor.commit();
Log.d("DEBUG","onConnected LoginGPlusFragment");
mSignInClicked = false;
launchChatActivity();
}
And i delete it in my disconnect method
// Google log out
if(LoginGPlusFragment.mGoogleApiClient.isConnected())
LoginGPlusFragment.mGoogleApiClient.disconnect();
SharedPreferences sharedPref = getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("signed_in_with_google", false);
editor.commit();
returnToLoginScreen();
And then, I check in the onCreateView if my preference is true:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
Log.d("DEBUG","onViewCreated LoginGPlusFragment");
super.onViewCreated(view, savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope("profile"))
.build();
SharedPreferences pref = getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
boolean signed = pref.getBoolean("signed_in_with_google", false);
btnLogin = (SignInButton) view.findViewById(R.id.sign_in_button);
btnLogin.setOnClickListener(this);
if(signed)
{
Log.d("DEBUG","You were previously signed in with google.");
connect();
}
}

Google Plus login why onConnectionFailed is called:

Why onConnectionFailed is beign called? This is my code:
package com.example.app;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import java.util.HashMap;
/**
* Created by root on 15-3-1.
*/
public class GooglePlusSingIn extends Activity implements View.OnClickListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
/**
* GooglePlusSingIn vars
*/
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "GooglePlusSingIN";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
signInWithGplus();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
*/
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
setResult(Activity.RESULT_CANCELED);
finish();
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();
}else{
setResult(Activity.RESULT_CANCELED);
finish();
}
}
}
#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 onConnected(Bundle arg0) {
mSignInClicked = false;
finish();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
/**
* Button on click listener
*/
#Override
public void onClick(View v) {
}
/**
* Sign-in into google
*/
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
*/
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
/**
* Revoking access from google
*/
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e(TAG, "User access revoked!");
mGoogleApiClient.connect();
}
});
}
}
}
I am doing this by android hive's gplus tutorial and i am getting this problem. When i try this the WiFi of my phone is turned on. I've added my SHA1 certificate to the google dev console, so where is the problem?
clean the project and uninstall project from your device. Then install..
Its works for me

Google+ sign-in button on Android doesn't do anything when clicked

I am trying to implement Google+ login in my Android app.
I have followed the Google+ API tutorials. However, when I click the sign-in button, nothing happens, no dialog or prompt appears for login. Logcat is not showing any errors either. I cannot seem to understand why this is not working when I have followed the Google+ API docs.
Here is my code:
package com.chromiumapps.fost;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import static android.view.View.*;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
public class FostActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnClickListener {
/* Called when the activity is first created. */
/*
* public boolean Facebook = false; public boolean Twitter = false; public
* boolean Googleplus = false; public boolean Blogger = false;
*/
private MainFragment mainFragment;
SharedPreferences pref;
private static final int RC_SIGN_IN=0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getPreferences(0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("CONSUMER_KEY", CONSUMER_KEY);
edit.putString("CONSUMER_SECRET", CONSUMER_SECRET);
edit.commit();
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
//s = new ShareBarActivity();
//getSupportFragmentManager().beginTransaction()
//.add(android.R.id.content, s).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
//linkedInFragment = (LinkedIn_Fragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
setContentView(R.layout.main);
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, new Plus.PlusOptions.Builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
protected void onStart(){
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop(){
super.onStop();
if (mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
protected void onAcitivityResult(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 onConnected(Bundle arg0) {
// TODO Auto-generated method stub
mSignInClicked = false;
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
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();
}
}
}
protected void resolveSignInError(){
if(mConnectionResult.hasResolution()){
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution().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();
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.sign_in_button && !mGoogleApiClient.isConnecting()){
mSignInClicked=true;
resolveSignInError();
}
if(v.getId()==R.id.sign_out_button){
if(mGoogleApiClient.isConnected()){
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
}
}
Try this at mGoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApiIfAvailable(Drive.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN).build();

Intergrate Google Plus

I am going along with the tutorial , and am getting error: The method getIntentSender() is undefined for the type ConnectionResult in the onConnectionFailed class.
I want to integrate Google Plus on click of button,
Here is Full Code :
package com.example.demogoogleshare;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.PlusClient;
public class MainActivity extends Activity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
Button signIn_button;
GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
PlusClient mPlusClient;
/* 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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(Plus.API, null).addScope(Plus.SCOPE_PLUS_LOGIN).build();
signIn_button = (Button) findViewById(R.id.signIn_button);
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.signIn_button) {
Toast.makeText(getApplicationContext(), "signIn", 1000).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (!mIntentInProgress && result.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(result.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();
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
// We've resolved any connection errors. mGoogleApiClient can be used to
// access Google APIs on behalf of the user.
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
}
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 method write below code:
mPlusClientBuilder = new Builder(this, this, this);
mPlusClientBuilder.setScopes(Scopes.PLUS_LOGIN, Scopes.PROFILE);
mPlusClient = mPlusClientBuilder.build();
mPlusClient.connect();
//OnActivityResult method:
#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();
}
}
//OnConnectionFailed method:
#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();
}
}
}
//OnConnected method:
#Override
public void onConnected(Bundle arg0) {
String accountName = mPlusClient.getAccountName();
}
//SignIn Button click:
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();
}
}
});
// Share on google plus button click event:
btnShare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mPlusClient.isConnected()) {
mPlusShareBuilder = new PlusShare.Builder(getApplicationContext());
mPlusShareBuilder.setType("text/plain");
mPlusShareBuilder.setText(IN_SHARE_MESSAGE + IN_SHARE_LINK);
mPlusShareBuilder.setContentUrl(Uri.parse(IN_SHARE_LINK));
// Intent shareIntent =
// PlusShare.Builder.from(YOUR ACTIVITY.this).setText().setType("text/plain").setContent(Uri.parse("http://example.com/cheesecake/lemon"))
// .getIntent();
Intent shareIntent = mPlusShareBuilder.getIntent();
startActivityForResult(shareIntent, REQUEST_CODE_SHARE);
} else {
//print failure message here
}
}
});

Error clicking Google+ sign in button in Android application

I am trying to signin to to my app using Google+ play services.The code doesn't have any errors and it launches in the emulator.But when i click the "signin with google" button i get this error in the logcat
I am not sure why this happens.Here is my MainActivity class:
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.*;
import com.google.android.gms.plus.PlusClient;
public class MainActivity extends Activity implements View.OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener{
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private Button signInButton;
private ProgressDialog mConnectionProgressDialog;
private static PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlusClient = new PlusClient.Builder(this, this, this)
.setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/ BuyActivity")
.setScopes("PLUS_LOGIN") // Space separated list of scopes
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
signInButton =(Button) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(this);
}
public static PlusClient getPlusClientObject() {
return mPlusClient;
}
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
//signInButton =(Button) findViewById(R.id.sign_in_button);
//signInButton.setOnClickListener(this);
return true;
}
#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;
}
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) { //this is called when the user has successfully signed in
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
Intent logoutIntention = new Intent(this, LogoutActivity.class);
startActivity(logoutIntention);
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
}
and my app references google-play-services_lib which has this structure:
I am not sure why this is happening.Can anyone help?
Here is the definition of my emulator:

Categories

Resources