I am unable to signup in google plus in my android application. It is working fine in jelly bean and kitkat. It is not working in lollypop and above.
I am getting false in GoogleSignInResult result.success().
Below is my Code:
public class SignUp extends FragmentActivity implements
GoogleApiClient.OnConnectionFailedListener {
private ImageView google_button
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//initializes view
initializeViews();
//facebook login end
google_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.e("data g+", result.toString());
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.e(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e("authType", "googlePlus");
Log.e("authId", acct.getId());
Log.e("firstname", acct.getDisplayName());
Log.e("middlename", acct.getDisplayName());
Log.e("lastname", acct.getDisplayName());
Log.e("userpic", acct.getPhotoUrl() + "");
Log.e("email", acct.getEmail());
String[] DisplayName = acct.getDisplayName().split(" ");
String firstName = "";
String lastName = "";
if (DisplayName.length == 2) {
firstName = DisplayName[0];
lastName = DisplayName[1];
} else {
firstName = acct.getDisplayName();
}
String photoUrl = "";
if (acct.getPhotoUrl() != null) {
photoUrl = acct.getPhotoUrl().toString();
}
Bundle data = new Bundle();
data.putString("authType", "googlePlus");
data.putString("authId", acct.getId());
data.putString("firstname", firstName);
data.putString("middlename", "");
data.putString("lastname", lastName);
data.putString("userpic", photoUrl);
data.putString("email", acct.getEmail());
Intent intent = new Intent(SignUp.this, Register.class);
intent.putExtras(data);
startActivity(intent);
finish();
} else {
// Signed out, show unauthenticated UI.
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
public void initializeViews() {
register = (TextView) findViewById(R.id.register);
fb_button = (ImageView) findViewById(R.id.facebook_button);
google_button = (ImageView) findViewById(R.id.google_button);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("connectionResult", connectionResult.toString());
Toast.makeText(getApplicationContext(), getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
}
Related
I am doing sign in with Google account I have followed for creating a JSON file. Also I have integrate JSON file with my project.But I am getting exception that account.getDisplayName throws nullPointException.
Google sign in code:
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
private SignInButton signInButton;
private GoogleApiClient client;
private static final int REQ_CODE = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = (SignInButton)findViewById(R.id.btn_signin);
GoogleSignInOptions options = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestProfile()
.requestEmail()
.build();
client = new GoogleApiClient.Builder(this).
enableAutoManage(this,this).
addApi(Auth.GOOGLE_SIGN_IN_API,options).build();
signInButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_signin:
signIn();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void signIn(){
Intent intent = Auth.GoogleSignInApi.getSignInIntent(client);
startActivityForResult(intent,REQ_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE){
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
}
private void handleResult(GoogleSignInResult result) {
if (result.isSuccess()){
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String image = account.getPhotoUrl().toString();
}
}
}
and here is my compiled library:
implementation 'com.google.android.gms:play-services-auth:16.0.1'
please guide where I am doing mistake
Try this :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == REQ_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
// G+
Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
System.out.println("Display Name: " + person.getDisplayName());
System.out.println("Gender: " + person.getGender());
System.out.println("AboutMe: " + person.getAboutMe());
System.out.println("Birthday: " + person.getBirthday());
System.out.println("Current Location: " + person.getCurrentLocation());
System.out.println("Language: " + person.getLanguage());
}
}
If you want " UserName, Email Id, Profile URL, Google Id" of google.
You have done mistake with "GoogleSignInOptions". Please Replace my GoogleSignInOptions with your GoogleSignInOptions code to resolve your problem.
Then, Your Solution is here -> You should follow below code.
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 9001;
private LinearLayout googleBtn;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
googleBtn = view.findViewById(R.id.googleBtn);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.default_web_client_id))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(Objects.requireNonNull(getActivity()))
.enableAutoManage(getActivity(), 0, connectionResult -> {
Snackbar.make(googleBtn, "Connection failed..", Snackbar.LENGTH_SHORT).show();
Log.e(TAG, "Google connection Error: " + connectionResult.getErrorMessage());
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(#Nullable Bundle bundle) {
//Log.e(TAG,"mGoogleApiClient is connected");
mGoogleApiClient.clearDefaultAccountAndReconnect();
}
#Override
public void onConnectionSuspended(int i) {
}
})
.build();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.googleBtn:
//stopAutoManage first otherwise throws exception Already managing a GoogleApiClient with id 0
if (mGoogleApiClient != null) {
mGoogleApiClient.stopAutoManage(Objects.requireNonNull(getActivity()));
}
loginWithGoogle();
break;
}
public void loginWithGoogle() {
Log.e(TAG, "is connected? " + mGoogleApiClient.isConnected());
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
Objects.requireNonNull(getActivity()).startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
public void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
// Get account information
if (acct != null) {
Name = acct.getDisplayName();
if (acct.getEmail() != null) {
Email = acct.getEmail();
} else {
Email = "";
}
SocialUserId = acct.getId();
Gender = "";
String idToken = acct.getIdToken();
String profileURL = Objects.requireNonNull(acct.getPhotoUrl()).toString();
String status = "Status: \nFullname: " + Name + "\n Email: " + Email + "\nProfile URI: " + profileURL;
Log.i(TAG, "Google signin " + status);
Log.i(TAG, "ID Token: " + idToken);
Log.i(TAG, "ID: " + acct.getId());
//TODO Temporary "acct.getCompId()" pass "idToken"
checkIsUserExists();
}
} else {
hideProgressBar();
Log.e(TAG, "Failed!! Google Result " + result.getStatus());
int status_code = result.getStatus().getStatusCode();
switch (status_code) {
case GoogleSignInStatusCodes.SIGN_IN_CANCELLED:
Snackbar.make(googleBtn, "Google sign in has been cancelled.", Snackbar.LENGTH_SHORT).show();
break;
case GoogleSignInStatusCodes.NETWORK_ERROR:
Snackbar.make(googleBtn, "Application is unable to connect with internet", Snackbar.LENGTH_SHORT).show();
default:
//AppUtils.showSnackBar(LandingActivity.this, btnLogin, GoogleSignInStatusCodes.getStatusCodeString(result.getStatus().getStatusCode()), R.integer.snackbar_duration_3sec);
break;
}
}
}
You can follow these steps to integrate Google Sign In in your Android application
Step 1. Implement library
implementation 'com.google.android.gms:play-services-auth:17.0.0'
Step 2. Add google login button
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
Step 3. Add below code in your activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (SignInButton)findViewById(R.id.signup);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, google_login);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("called", "called");
if (requestCode == google_login) {
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Disaplay data on your screen
Log.e("email", account.getEmail());
Log.e("name", account.getDisplayName());
Log.e("id", account.getId());
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.e("signInResult", ":failed code=" + e.getStatusCode());
}
}
You can follow this tutorial for complete implementation :- Sign In with Google in your Android Application
i am using Google Api Clint for login with google account. my code is working fine, but when i am trying to sign out from a fragment Logout.java, its not working please see my login Activity code below.
in oncreate
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
And rest of the Code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e(TAG, "display name: " + acct.getDisplayName());
String personName;
//String personPhotoUrl = acct.getPhotoUrl().toString();
String email;
String gid;
String location = "Location Not Set";
String oarth = "Google";
String gender = "Not Set";
if(acct.getDisplayName() != null){
personName = acct.getDisplayName();
}else{
personName ="";
}
if(acct.getEmail() != null){
email = acct.getEmail();
}else{
email ="";
}
if(acct.getId() != null){
gid = String.valueOf(acct.getId());
}else{
gid ="";
}
Log.e(TAG, "Name: " + personName + ", email: " + email
+ ", id: " + gid +", location:" +location+", oarth: "+oarth+", gender: "+gender);
//session.setMember(gid, personName, location, gender, email, oarth);
InsertFbLogindata(gid, personName, location, gender, email, oarth);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
case R.id.btn_sign_out:
signOut();
break;
case R.id.btn_revoke_access:
revokeAccess();
break;
}
}
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
}
}
in my logout Fragment
public class logout extends Fragment {
Button Logout;
Session session;
LoginActivity la;
private GoogleApiClient mGoogleApiClient;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.sent_layout,container,false);
final Button logout = (Button)root.findViewById(R.id.buttonLogout);
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
session = new Session(getActivity());
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
session.setLogin(false);
LoginManager.getInstance().logOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
return root;
}
}
i tried so many examples but no use. is there any possible to this. please suggest the best way.
your activity code is absolutely fine but in login.java, you have to change some code as follows.
get instance of googlesigninoptions
firebase authentication
that's it you can call `mAuth.signout()
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient=GoogleSignIn.getClient(
getActivity(),gso);
mAuth=FirebaseAuth.getInstance();
mGoogleSignInClient.signOut().
addOnCompleteListener(getActivity(),
new OnCompleteListener<Void>()
{
#Override
public void onComplete (#NonNull Task < Void > task) {
SharedPreferences getUser = getActivity().getSharedPreferences("user_info", getActivity().MODE_PRIVATE);
SharedPreferences.Editor ed = getUser.edit();
ed.putString("username", null);
ed.commit();
Snackbar.make(v.getRootView().findViewById(R.id.settings_fragment_layout), "Logged Out Successfully", Snackbar.LENGTH_SHORT).show();
HomeFragment hf = new HomeFragment();
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, hf)
.commit();
}
});
I want to integrate Google sign in to my game. But i don't want to make sign in process with a button I want it happen once user opens application.
Whenever MenuActivity is created it asks to choose an account to sign in. But I want it to choose account only once (first time) and remember every time. Here is code:
public class MenuActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
if(!mGoogleApiClient.isConnected()){
signIn();
}
}
public void startGame(View view){
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
} else {
}
}
}
First create SharedPreferences
public void saveUser (String key, String value ) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.commit();
}
public String getUser (String key) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
return pref.getString(key, "");
}
Check user's email if it is empty add SharedPreferences
if(!mGoogleApiClient.isConnected() && getUser("email").isEmpty() ){
signIn();
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
saveUser("email", acct.getEmail());
saveUser("name", acct.getDisplayName());
} else {
}
}
My app consists of google login feature, when ever the user clicks the sign in button, i need to fetch user name and emailId using googleapiclient. When i run the debug apk, i'm getting all required details that i need, but when it came to release apk, i'm not able to fetch the details instead i'm getting handleSignInResult:false
Here is the code of my signin class file:-
public class SignIn extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = SignIn.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private LinearLayout llProfileLayout;
private TextView txtName, txtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e(TAG, "display name: " + acct.getDisplayName());
String personName = acct.getDisplayName();
String email = acct.getEmail();
Log.e(TAG, "Name: " + personName + ", email: " + email);
txtName.setText(personName);
txtEmail.setText(email);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
case R.id.btn_sign_out:
signOut();
break;
case R.id.btn_revoke_access:
revokeAccess();
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
}
And here is the log report of release apk
handleSignInResult:false
Check you file google-service.json
You must add SHA1 from release.keystore not android_debug.keystore
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private LinearLayout llProfileLayout;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e(TAG, "display name: " + acct.getDisplayName());
String personName = acct.getDisplayName();
String personPhotoUrl = acct.getPhotoUrl().toString();
String email = acct.getEmail();
Log.e(TAG, "Name: " + personName + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
Glide.with(getApplicationContext()).load(personPhotoUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfilePic);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
case R.id.btn_sign_out:
signOut();
break;
case R.id.btn_revoke_access:
revokeAccess();
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
}
Please give me in detail answer about why we use The constant in this
Why we use A Constant int RC_SIGN_IN = 007
private static final int RC_SIGN_IN = 007
There could be many activities which you can start to get some sort of result from an activity and you receive those results in only one method of the activity i.e onActivityResult().
In order to differentiate which type of result you have received you make use of Request codes, which is in-fact just a unique constant integer.
So When the Google sign in process returns the sign-in result (success or failure) it returns using the request code so that you can check the result which you just received is a Sig-in result and get the data in the required data type.