How to Signout GoogleApiClint from another Activity or Fragment android - android

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();
}
});

Related

Google Sign In for Android: Cannot resolve RC_SIGN_IN

I'm trying to authenticate with backend server from mobile app.
I was following this documentation. https://developers.google.com/identity/sign-in/android/sign-in
However, there are some errors. RC_SIGN_IN and updateUI() cannot be resolved.
My code is like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mSignInButton = findViewById(R.id.sign_in_button);
mSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_LONG).show();
Intent signIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signIntent, RC_SIGN_IN);
}
});
#Override
protected void onStart() {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
super.onStart();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
// Send Id Token to the backend and validate here
// Signed in successfully, show authenticated UI.
updateUI(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
Update
Now the button itself doesn't work.
xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Include the main content -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
<!-- Navigation bar -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/navigation_menu"/>
</android.support.v4.widget.DrawerLayout>
How can I fix this?
You need to do nothing but replace RC_SIGN_IN with an int value. It can be anything but use 1 as it's value. Do as follows:
startActivityForResult(signIntent, 1);
And change the if code in activity result as follows:
if (requestCode == 1)
Also change the sign in button click code to this(remove switch cases):
mSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
}
});
This is because you are calling on click method to the button and then again checking If the same button is clicked, that's why I think it's not working.
Now for the updateUI method, this method should be defined by you. Basically, this is for your app to change what is shown to the user when he/she has signed into the app. If you want to open new activity when signedIn() you can use Intent by changing the updateUI(account) in the activity result and onstart event to an intent:
startActivity(new Intent(MainActivity.this, SecondActivity.class));
And get which account is signedin in the SecondActivity:
GoogleSignInAccount account = GoogleSignIn.g etLastSignedInAccount(this); //use this in onCreate
Try this one.
In MainActivity, implement View.OnClickListener and GoogleApiClient.OnConnectionFailedListener
private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
private GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
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)
.into(imgProfilePic);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
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);
}
});
}
#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) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
RC_SIGN_IN is basically an int number code that is used to identify that your onActivityResult is called for google sign-in.
private static final int RC_SIGN_IN = 007;
updateUi() is method used to let user know that google Signin is successfull or not. Here is method:
private void updateUI(GoogleSignInAccount signedIn) {
if (signedIn != null) {
// sigin is successfull
signInButton.setVisibility(View.GONE);
signOutButton.setVisibility(View.VISIBLE);
} else {
// sigin is cancelled
signInButton.setVisibility(View.VISIBLE);
signOutButton.setVisibility(View.GONE);
}
}

How to Logout from google account using menu item in my android app

In My Application i am working with google account login here my requirement is I want to logout from the app using menu item (logout).
Here is my login Activity code:
btnSignIn.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);
}
public void signOut() {
Auth.GoogleSignInApi.signOut(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());
personName = acct.getDisplayName();
email = acct.getEmail();
Log.e(TAG, "Name: " + personName + ", email: " + email);
try {
personPhotoUrl = acct.getPhotoUrl().toString();
Glide.with(getApplicationContext()).load(personPhotoUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfilePic);
} catch (Exception e) {
imgProfilePic.setImageResource(R.mipmap.user1);
}
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_sign_in:
signIn();
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()) {
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
the sign-in has expired,
silently. Cross-device
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
Intent intent = new Intent(LoginActivity.this, OtpVerfication.class);
intent.putExtra("username",personName);
intent.putExtra("email",email);
intent.putExtra("picture",personPhotoUrl);
startActivity(intent);
overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
finish();
}
here i want logout from the app using menu item for this i am calling signout method from the menu item(logout).
I searched for this and i found some solutions, but there no use anyone help me to solve this problem.
There are actually options for logOut/SignOut.
AS the Docs states you can sign out users using signOut() method on googleSignInClient
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
here in onComplete(), you can check if it was a failure or success as well as checking which account it was.
even further if you like to delete your app from his account (technically removing your apps access to the user's account) you can do so using revokeAccess() method:
mGoogleSignInClient.revokeAccess()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
As revokeAccess() is highly recommended I suggest you provide an option for the user for this method

AuthResult task in google sign in returning false in task.isSuccess statement

I had implemented Google Signin with my app using Firebase.
As the user signed in, the MainActivity should start.
But this statement in my firebaseAuthWithGoogle() function is returning false as:
if (task.isSuccessful()) {
//Start The activity from here
}
Here's my login.java that is causing me this:
public class login extends AppCompatActivity {
private SignInButton signInButton;
private TextView textView;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
startActivity(new Intent(login.this, MainActivity.class));
}
}
};
signInButton = findViewById(R.id.SignIn);
textView = findViewById(R.id.negativetext);
textView.setText(getString(R.string.negativetext));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#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) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
//Toast.makeText(getApplicationContext(), ""+account, Toast.LENGTH_LONG).show();
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w("Signing in: ", "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
Toast.makeText(getApplicationContext(), "" + credential, Toast.LENGTH_LONG).show();
//mAuth = FirebaseAuth.getInstance();
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "" + task.isSuccessful(), Toast.LENGTH_LONG).show();
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
//Log.d(TAG, "signInWithCredential:success");
//FirebaseUser user = mAuth.getCurrentUser();
//Log.i("Test:", " Compiled ?");
//startActivity(new Intent(login.this, MainActivity.class));
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
startActivity(new Intent(login.this, MainActivity.class));
//updateUI(user);
} else {
Toast.makeText(getApplicationContext(), "Not Success", Toast.LENGTH_LONG).show();
//Log.w(TAG, "signInWithCredential:failure", task.getException());
//Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
// Toast.makeText(getApplicationContext(), ""+acct, Toast.LENGTH_LONG).show();
}
}
Can anyone suggest/advice what am i doin' wrong here?
I checked the statements, so i commented some of the lines.
Any regarding advice would be very much appreciated :)
This is happening because you are using the following line of code twice:
startActivity(new Intent(login.this, MainActivity.class));
Once in your mAuthListener and once in your firebaseAuthWithGoogle() method. You need to redirect the user to the MainActivity only when the firebaseAuth.getCurrentUser() != null, which means that the user is already authenticated. I have explained in one of my tutorials all the steps hat you need to follow in order the achieve the exact thing that you are looking for.

Google SignIn Issue in release apk

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

Why we use A Constant int RC_SIGN_IN = 007

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.

Categories

Resources