I am having problem while implementing Google +1 button in my android application.
I followed instruction on this link and my activity is showing g+ button successfully but after clicking on button, it is showing a progress bar on the button only, please tell me how +1 button works in android it should open a login internet or what?
I am not implementing signin with google just +1 button in my app. Hhere is my code, this is part of my code so it is not that proper.
public class as {
private static final String URL = "www.app.in";
private static final int PLUS_ONE_REQUEST_CODE = 10;
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private PlusOneButton mPlusOneButton;
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.product_details);
setCurrentContext(this);
super.onCreate(savedInstanceState);
mPlusOneButton = (PlusOneButton) findViewById(R.id.googleplus);
mPlusClient = new PlusClient.Builder(this, this, this).clearScopes()
.build();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "OnStart");
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop");
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed");
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) {
Log.d(TAG, "onActivityResult");
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();
Log.d(TAG, "onConnected");
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
}
You need to be signed in for this to work, but you do not have to have a sign in button on your app.
If it is enabled (you can click on it) then you are already signed in and I suggest you check that you have specified a valid url.
Your code looks different to mine (I use a GameHelperListener) but as long as you have followed the documentation accurately it should be fine.
If you want to see it work, just download an app that has a +1 button on it, and try it.
Change url like
url="https://market.android.com/details?id=xxx.xxx.xxx";
Also implement methods
ConnectionCallbacks, OnConnectionFailedListener and extends activity
Related
I have this activity:
public class AMLoginActivity extends Activity implements IAsyncResponse {
public static int finished;
private final String TAG = "AMLoginActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finished = 0;
Intent i = new Intent(AMLoginActivity.this, GDLoginActivity.class);
i.putExtra("response", this);
AMLoginActivity.this.startActivity(i);
}
public void processFinish(){
finished++;
Log.i(TAG, "Number finished: " + finished);
if(finished == 1){
Log.i(TAG, "All finished");
AMLoginActivity.this.finish();
Log.i(TAG, "Finish called");
}
}
Which calls the GDLoginActivity to login to google drive. It can be seen below:
public class GDLoginActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "GDLoginActivity";
private static final int REQUEST_CODE_RESOLUTION = 3;
private static GoogleApiClient mGoogleApiClient;
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Log.i(TAG, "New GDClient created");
}
// Connect the client.
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
IAsyncResponse response = (IAsyncResponse) getIntent().getSerializableExtra("response");
Log.i(TAG, "Process finish");
response.processFinish();
finish();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
public static GoogleApiClient getGoogleApiClient(){
return mGoogleApiClient;
}
}
The issue is that when the GDLoginActivity connects and finish()'s, it should increment finish by 1 and and also finish the AMLoginActivity. It does increment by 1 and call finish() in processFinish(), but nothing happens and AMLoginActivity doesn't actually close (i.e. onDestroy() is never called), so i'm just left with a blank screen. If I remove GDLoginActivity and just call processFinish() instead, then AMLoginActivity finishes just fine, so I assume it has something to do with GDLoginActivity, but this is happening with other similar activities too. Any ideas?
Edit: Also if I hit the back button on the blank screen, then it calls the onDestroy() method of AMLoginActivity and goes to the activity I want, if that hints a clue at what is going on?
It looks like you're finishing them in a weird order. Try finishing the visible activity before you finish the one that started it.
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
IAsyncResponse response = (IAsyncResponse) getIntent().getSerializableExtra("response");
Log.i(TAG, "Process finish");
//finishes the previous activity
response.processFinish();
//finishes the visible activity
finish();
//try flipping this order ^
}
You could use startActivitForResult() if you're trying to finish one activity after another has finished.
I been getting an error trying to execute this Android Drive API example googledrive/android-quickstart, the app run fine then shows a windows dialog to select the google account, I select one and in logcat I get this:
I/drive-quickstart﹕ GoogleApiClient connection failed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{44c22a28: android.os.BinderProxy#44c1b1c0}}
Then shows the dialog again seems like a infinite loop
I have been already configured the OAuth and other parameters in google developer console.
Here is my code Thanks in advance..
public class CloudPaintActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = mBitmapToSave;
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
// If the operation was not successful, we cannot do anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle("Android Photo.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addApi(Plus.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
// if the api client existed, we terminate it
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// Just start the camera again for another photo.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
return;
}
saveFileToDrive();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
}
Try this if you don't need multiple accounts:
public class MainActivity extends AppCompatActivity {
private static final int REQ_CONNECT = 1;
private Activity mAct;
private static GoogleApiClient mGAC;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
mAct = this;
setContentView(R.layout.activity_main);
if (bundle == null) try {
mGAC = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override public void onConnectionSuspended(int i) { }
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(mAct, "bingo", Toast.LENGTH_LONG).show(); // connected
saveFileToDrive();
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connResult) {
if (connResult != null) {
if (!connResult.hasResolution()) {
int errCode = connResult.getErrorCode();
GooglePlayServicesUtil.getErrorDialog(errCode, mAct, 0).show();
return;
} else try {
connResult.startResolutionForResult(mAct, REQ_CONNECT);
return;
} catch (Exception e) { e.printStackTrace(); }
}
finish(); //--- FAIL - no resolution ---------->>>
}
})
.build();
} catch (Exception e) { e.printStackTrace(); }
}
#Override
protected void onResume() { super.onResume();
mGAC.connect();
}
#Override
protected void onPause() { super.onPause();
mGAC.disconnect();
}
#Override
protected void onActivityResult(int request, int result, Intent data) {
switch (request) {
case REQ_CONNECT:
if (result == RESULT_OK)
mGAC.connect();
else
finish(); //--- FAIL, user cancelled ------------->>>
break;
}
super.onActivityResult(request, result, data);
}
}
If you need to switch multiple accounts, add:
.addApi(Plus.API)
to your builder and call:
Plus.AccountApi.clearDefaultAccount(mGAC);
from wherever (menu for instance). Then create a new instance of mGAC and connect. It will pop up the account selection dialog again. But your app will not know which account the user selected (or created).
If you need to know your current user, you can drop the the Plus.API and manage the GooDrive accounts yourself with Account Picker, but you need to implement an Account Manager and instantiate mGAC with
.setAccountName([ACCOUNT EMAIL])
as seen here (follow the REQ_ACCPICK and see the Account Manager UT.AM).
Good Luck
Based off your error, it seems for whatever reason it fails to sign in. I believe in this case you should check if hasResolution returns true. If so, you can call [startResolutionForResult](https://developers.google.com/android/reference/com/google/android/gms/common/ConnectionResult.html#startResolutionForResult(android.app.Activity, int)) which will prompt the user to sign in.
As far why it fails to sign in, it's a bit difficult to tell. It sounds like you're using the AccountPicker? Perhaps you can try with only a single account signed into the device.
I have observed the behavior you describe when the OAuth 2.0 client ID set up on the Google Cloud console did not match the apk I was trying to run, either by Signing-certificate fingerprint or by Package name.
I want to get user circle's list of visible friends name and email address with Google Plus.
I have done following code and tried with 4 to 5 phone but in all I am getting zero list
class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, ResultCallback<People.LoadPeopleResult> {
private static final int RC_SIGN_IN = 22;
private static final String TAG = null;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle arg0) {
System.out.println("onConnected");
Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(
this);
}
#Override
public void onResult(LoadPeopleResult peopleData) {
System.out.println("onResult");
if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
PersonBuffer personBuffer = peopleData.getPersonBuffer();
try {
System.out.println("PersonBuffer : - "
+ personBuffer.getCount()); <=======HERE I AM GETTING ALWAYS 0
int count = personBuffer.getCount();
for (int i = 0; i < count; i++) {
Log.d(TAG, "Display name: "
+ personBuffer.get(i).getDisplayName());
}
} finally {
personBuffer.close();
}
} else {
Log.e(TAG,
"Error requesting visible circles: "
+ peopleData.getStatus());
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
Please check the following cases below
On the Consent Screen, you don't select circle which allow to see in your app
1.1 When the consent screen is showing after login to google+ in your app,
Click on the first sentence 'Know your basic profile info and list of people in your circle'
1.2 Be sure that you select 'All circles', or any non-empty circle
Your google+ account was set disallow your app to see the people in circle
2.1 Open Google+ app
2.2 Select 'Settings'
2.3 In the 'Account Settings' section, Select your account
2.4 Select 'Apps with Google+ Sign-in'
2.5 Select 'All apps & devices'
2.6 Select your app
2.7 In the 'This app can see these people', Be sure that it select 'All circles' or any non-empty circle.
2.8 For more detail, see the 'Change your Google+ Sign-In settings', In the 'Manage who in your circles the app can view' section in link below
https://support.google.com/plus/answer/2980770?hl=en
Here i am doing google + integartion.i am using the following code but i am facing the error which is : onConnectionFailed: ConnectionResult.getErrorCode() = 4.So please anybody help me and tell me what i am doing wrong in this code and provide me the solution for this.i will be very thankful to you.I searched a lot but found nothing.I am using the quick sample of Google plus.There is also another problem i am not able to personal information like birthday etc in this code.
public class GooglePlus extends FragmentActivity implements
ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener {
String fb_userId, fb_username;
SharedPreferences pref;
SharedPreferences.Editor editor;
private static final int STATE_DEFAULT = 0;
private static final int STATE_SIGN_IN = 1;
private static final int STATE_IN_PROGRESS = 2;
private static final int RC_SIGN_IN = 0;
private static final int DIALOG_PLAY_SERVICES_ERROR = 0;
private static final String SAVED_PROGRESS = "sign_in_progress";
// GoogleApiClient wraps our service connection to Google Play services and
// provides access to the users sign in state and Google's APIs.
private GoogleApiClient mGoogleApiClient;
// We use mSignInProgress to track whether user has clicked sign in.
// mSignInProgress can be one of three values:
//
// STATE_DEFAULT: The default state of the application before the user
// has clicked 'sign in', or after they have clicked
// 'sign out'. In this state we will not attempt to
// resolve sign in errors and so will display our
// Activity in a signed out state.
// STATE_SIGN_IN: This state indicates that the user has clicked 'sign
// in', so resolve successive errors preventing sign in
// until the user has successfully authorized an account
// for our app.
// STATE_IN_PROGRESS: This state indicates that we have started an intent to
// resolve an error, and so we should not start further
// intents until the current intent completes.
private int mSignInProgress;
// Used to store the PendingIntent most recently returned by Google Play
// services until the user clicks 'sign in'.
private PendingIntent mSignInIntent;
// Used to store the error code most recently returned by Google Play
// services
// until the user clicks 'sign in'.
private int mSignInError;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_plus);
pref = PreferenceManager.getDefaultSharedPreferences(this);
if (savedInstanceState != null) {
mSignInProgress = savedInstanceState.getInt(SAVED_PROGRESS,
STATE_DEFAULT);
}
mGoogleApiClient = buildGoogleApiClient();
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// resolveSignInError();
}
});
}
}, 1500);
}
private GoogleApiClient buildGoogleApiClient() {
// When we build the GoogleApiClient we specify where connected and
// connection failed callbacks should be returned, which Google APIs our
// app uses and which OAuth 2.0 scopes our app requests.
return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVED_PROGRESS, mSignInProgress);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes
// might
// be returned in onConnectionFailed.
Log.i("", "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
if (mSignInProgress != STATE_IN_PROGRESS) {
// We do not have an intent in progress so we should store the
// latest
// error resolution intent for use when the sign in button is
// clicked.
mSignInIntent = result.getResolution();
mSignInError = result.getErrorCode();
if (mSignInProgress == STATE_SIGN_IN) {
// STATE_SIGN_IN indicates the user already clicked the sign in
// button
// so we should continue processing errors until the user is
// signed in
// or they click cancel.
resolveSignInError();
}
}
// In this sample we consider the user signed out whenever they do not
// have
// a connection to Google Play services.
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
/*
* Starts an appropriate intent or dialog for user interaction to resolve
* the current error preventing the user from being signed in. This could be
* a dialog allowing the user to select an account, an activity allowing the
* user to consent to the permissions being requested by your app, a setting
* to enable device networking, etc.
*/
private void resolveSignInError() {
if (mSignInIntent != null) {
// We have an intent which will allow our user to sign in or
// resolve an error. For example if the user needs to
// select an account to sign in with, or if they need to consent
// to the permissions your app is requesting.
try {
// Send the pending intent that we stored on the most recent
// OnConnectionFailed callback. This will allow the user to
// resolve the error currently preventing our connection to
// Google Play services.
mSignInProgress = STATE_IN_PROGRESS;
startIntentSenderForResult(mSignInIntent.getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i("",
"Sign in intent could not be sent: "
+ e.getLocalizedMessage());
// The intent was canceled before it was sent. Attempt to
// connect to
// get an updated ConnectionResult.
mSignInProgress = STATE_SIGN_IN;
mGoogleApiClient.connect();
}
} else {
// Google Play services wasn't able to provide an intent for some
// error types, so we show the default Google Play services error
// dialog which may still start an intent on our behalf if the
// user can resolve the issue.
showDialog(DIALOG_PLAY_SERVICES_ERROR);
}
}
#SuppressWarnings("unused")
#Override
public void onConnected(Bundle arg0) {
// Reaching onConnected means we consider the user signed in.
Log.i("onConnected", "onConnected");
// Retrieve some profile information to personalize our app for the
// user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentUser.getDisplayName();
String personPhotoUrl = currentUser.getImage().getUrl();
String personGooglePlusProfile = currentUser.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.i("personName", personName);
Log.i("email", email);
Log.i("Gender", "" + currentUser.getGender());
Log.i("Birthday", "" + currentUser.getBirthday());
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT;
/*
* fb_userId = currentUser.getId(); fb_username =
* currentUser.getDisplayName(); editor = pref.edit();
* editor.putString("fb_userId", fb_userId);
* editor.putString("fb_username", fb_username);
* editor.putString("social_provider", "google +");
*
* editor.putString("gender", currentUser.getGender());
* editor.putString("birthday", currentUser.getBirthday());
*
* editor.putString("device_name", "android");
*
* editor.putString("email",
* Plus.AccountApi.getAccountName(mGoogleApiClient)); editor.commit();
*/
}
#Override
public void onConnectionSuspended(int arg0) {
// The connection to Google Play services was lost for some reason.
// We call connect() to attempt to re-establish the connection or get a
// ConnectionResult that we can attempt to resolve.
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
if (resultCode == RESULT_OK) {
// If the error resolution was successful we should continue
// processing errors.
mSignInProgress = STATE_SIGN_IN;
} else {
// If the error resolution was not successful or the user
// canceled,
// we should stop processing errors.
mSignInProgress = STATE_DEFAULT;
}
if (!mGoogleApiClient.isConnecting()) {
// If Google Play services resolved the issue with a dialog then
// onStart is not called so we need to re-attempt connection
// here.
mGoogleApiClient.connect();
}
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PLAY_SERVICES_ERROR:
if (GooglePlayServicesUtil.isUserRecoverableError(mSignInError)) {
return GooglePlayServicesUtil.getErrorDialog(mSignInError,
this, RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Log.e("",
"Google Play services resolution cancelled");
mSignInProgress = STATE_DEFAULT;
}
});
} else {
return new AlertDialog.Builder(this)
.setMessage(R.string.play_services_error)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Log.e("",
"Google Play services error could not be "
+ "resolved: "
+ mSignInError);
mSignInProgress = STATE_DEFAULT;
// mStatus.setText(R.string.status_signed_out);
}
}).create();
}
default:
return super.onCreateDialog(id);
}
}
}
I had the same problem. I solved in google api console >> consent screen, and adding a Product Name.
I try this tutorial: http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
In the main activity you need change .addApi(Plus.API, null) by .addApi(Plus.API, Plus.PlusOptions.builder().build())
For me the problem was that I had not created the credentials for the app.
Went to Google Developers Console > Credentials > Create New Client ID
filled the corresponding package name and SHA1 for my app, reran the app and then it worked!
In case you are using MapView, make sure you are following the guidelines
i.e.
"When using the API in fully interactive mode, users of this class must forward all the activity life cycle methods to the corresponding methods in the MapView class. Examples of the life cycle methods include onCreate(), onDestroy(), onResume(), and onPause(). When using the API in lite mode, forwarding lifecycle events is optional. For details, see the lite mode documentation."
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
I'm trying to implement the login with Google+ in my firt activity of my application. I followed the google dev tutorial but when I click on the SignIn button nothing happens. I think I've made some mistakes, here the code:
public class MainActivity extends FragmentActivity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
public static final String mAPP_ID = "xxxx";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private static final String TAG = "MainActivity";
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private ImageButton googleSignOutButton;
AssetsExtracter mTask;
private MainFragment mainFragment;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mPlusClient = new PlusClient.Builder(this, this, this)
.setActions("http://schemas.google.com/AddActivity")
.setScopes(Scopes.PLUS_LOGIN)
.build();
// Progress bar to be displayed if the connection failure is not
// resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
mTask = new AssetsExtracter();
mTask.execute(0);
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
#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(Bundle connectionHint) {
// We've resolved any connection errors.
mConnectionProgressDialog.dismiss();
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
if (requestCode == REQUEST_CODE_RESOLVE_ERR
&& responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in_button
&& !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(
getParent(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
}
EDIT:
I've discovered that in the onConncectionFailed() method, if I remove the first "if()" that checks if the processDialog is showing, when the application starts, without clicking anything, a dialog of google+ appears asking me to login. this is strange
EDIT:
I resolved my problem using a normal Button and implementing onClick on it, following the tutorial of Google Dev
Have you registered your application on the Google developers console? You need to make sure your Android application has an associated client ID with the Google+ API enabled.
https://developers.google.com/+/mobile/android/getting-started#step_1_enable_the_google_api
After doing some digging I realised that providing the release SHA-1 to the console only gave me the ability to run my project with a working sign-in button if and only I generated a signed APK and installed the APK manually and not through Android Studio.
I figured changing the SHA-1 to debug was the solution but I wasn't able to change it until now.
To change your SHA-1 from the release version to the debug version so you can install a working/testable apk through Android Studio:
Open Google Cloud Console > Open API Manager > Click on Credentials.
Under OAuth2.0 Client IDs > click Android Client for your app and change the SHA-1 to your debug version (following these instructions should help you to retrieve your debug SHA-1: https://developer.android.com/studio/publish/app-signing.html)
After doing so, save your new credentials in the Cloud Console and return to the screen to generate your configuration file. You should notice your changed SHA-1. Now generate the config file and paste it into app/.. project directory. Clean, rebuild, and run your project and your signin button should now work as expected.