我正在使用Firebase和Google登录。问题是,当我单击登录按钮时,即使没有在Firebase身份验证用户中注册任何Google帐户,它也会自动登录!当用户不在Firebase身份验证用户中时,也不会出现“选择帐户”对话框。我想显示此对话框。
LoginActivity
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.schooltest.MainActivity;
import com.example.schooltest.R;
import com.example.schooltest.ResetPasswordActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shobhitpuri.custombuttons.GoogleSignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
//check the current user
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.et_email_address);
inputPassword = (EditText) findViewById(R.id.et_password);
final Button ahlogin = (Button) findViewById(R.id.login_btn);
progressBar = (ProgressBar) findViewById(R.id.loading_spinner);
TextView btnForgot = findViewById(R.id.forgot);
TextView btnSignUp = (TextView) findViewById(R.id.signup_here_Button);
button = (GoogleSignInButton) findViewById(R.id.login_google_btn);
mViewHelper = findViewById(R.id.view_helper);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnForgot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
mAuth = FirebaseAuth.getInstance();
// Checking the email id and password is Empty
ahlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Email is required.", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_SHORT).show();
return;
}
if(password.length() < 6) {
inputPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
ahlogin.setVisibility(View.INVISIBLE);
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
ahlogin.setVisibility(View.VISIBLE);
if (task.isSuccessful()) {
// there was an error
Log.d(TAG, "signInWithEmail:success");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Log.d(TAG, "singInWithEmail:Fail");
Toast.makeText(LoginActivity.this, getString(R.string.failed), Toast.LENGTH_LONG).show();
}
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("430102477506-gsgi3mjgd1bie5ml5nf316no2ki3llvj.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
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);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
SignUpActivity
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.schooltest.MainActivity;
import com.example.schooltest.R;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shobhitpuri.custombuttons.GoogleSignInButton;
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String name = mName.getText().toString().trim();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("430102477506-gsgi3mjgd1bie5ml5nf316no2ki3llvj.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
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);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
主要活动
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.example.schooltest.login.LoginActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private String mName;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ClassFragment()).commit();
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Sets default values only once, first time this is called. The third
// argument is a boolean that indicates whether the default values
// should be set more than once. When false, the system sets the default
// values only the first time it is called.
PreferenceManager.setDefaultValues(this,
R.xml.pref_students, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_information, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_security, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_notifications, false);
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(MainActivity.this, FullscreenActivity.class);
startActivity(startIntent);
finish();
}
/**
* Inflates the menu, and adds items to the action bar if it is present.
*
* @param menu Menu to inflate.
* @return Returns true if the menu inflated.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/**
* Handles app bar item clicks.
* Don't forget to add intent to addstudent
* @param item Item clicked.
* @return True if one of the defined items was clicked.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addStudent:
displayToast(getString(R.string.action_addStudent_message));
return true;
case R.id.action_settings:
Intent settingsIntent = new Intent(this,
SettingsActivity.class);
startActivity(settingsIntent);
return true;
case R.id.menu_logout_btn:
FirebaseAuth.getInstance().signOut();
sendToStart();
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
/**
* Displays a Toast with the message.
*
* @param message Message to display
*/
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_class:
selectedFragment = new ClassFragment();
break;
case R.id.navigation_due:
selectedFragment = new DueFragment();
break;
case R.id.navigation_messages:
selectedFragment = new MessagesFragment();
break;
case R.id.navigation_class_updates:
selectedFragment = new ClassUpdatesFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}