我有一个非常基本的问题要问。我是Android应用程序开发的新手。我严格遵循来源的教程说明。但是当存储用户数据时,我的导师使用的是parse.com。但是parse.com将在明年关闭,因此该选项将被关闭。所以我决定使用firebase,现在我安装了所有需要的包。 我想在firebase上为我的应用中的注册页面添加电子邮件/密码身份验证。请提供我应该添加的代码,并请说明应该放置的位置(例如,在oncreate下) 以及我应该初始化的东西
谢谢!
答案 0 :(得分:-1)
以下是我的LoginActivity类代码,其中包含使用Google帐户登录的信息,请参阅https://firebase.google.com/docs/auth/web/password-auth
中的详细信息public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private EditText txtEmail;
private EditText txtPass;
private Button btnLogin;
private Button btnRegister;
private ProgressDialog mProgress;
//firebase
private FirebaseAuth firAuth;
private DatabaseReference firDatabaseUsers;
//gogle sign in
private SignInButton mGoogleBtn;
private static final int RC_SIGN_IN = 1;
private static final String TAG = "LoginActivity";
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firAuth = FirebaseAuth.getInstance();
firDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
firDatabaseUsers.keepSynced(true);
txtEmail =(EditText) findViewById(R.id.logintxtEmail);
txtPass = (EditText) findViewById(R.id.logintxtPass);
btnLogin = (Button) findViewById(R.id.loginbtnEnter);
btnLogin.setOnClickListener(this);
mGoogleBtn = (SignInButton) findViewById(R.id.googlebtn);
mGoogleBtn.setOnClickListener(this);
mProgress = new ProgressDialog(this);
// ---------- GOOGLE SIGN IN ------------
// Configure Google Sign In
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) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.loginbtnEnter) {
checkLogin();
}
else if(view.getId() == R.id.googlebtn) {
signInGoogle();
}
}
private void signInGoogle() {
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) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
mProgress.setMessage("Iniciando sesión...");
mProgress.show();
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
mProgress.dismiss();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
firAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Autenticación Fallida.",
Toast.LENGTH_SHORT).show();
}
else {
mProgress.dismiss();
checkUserExist();
}
// ...
}
});
}
private void checkLogin () {
String _email = txtEmail.getText().toString().trim();
String _pass = txtPass.getText().toString().trim();
if(!TextUtils.isEmpty(_email) && !TextUtils.isEmpty(_pass)) {
mProgress.setMessage("Comprobando");
mProgress.show();
firAuth.signInWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful() ) {
mProgress.dismiss();
checkUserExist();
}
else {
mProgress.dismiss();
Toast.makeText(LoginActivity.this, "Error al ingresar", Toast.LENGTH_LONG).show();
}
}
});
}
}
private void checkUserExist () {
if(firAuth.getCurrentUser() != null) {
final String _user_id = firAuth.getCurrentUser().getUid();
firDatabaseUsers.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(_user_id)) {
Intent iSetup = new Intent(LoginActivity.this, MainActivity.class);
iSetup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(iSetup);
} else {
Intent iSetup = new Intent(LoginActivity.this, MainActivity.class);
iSetup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(iSetup);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
要注册用户,您需要运行此代码
final String _name = txtName.getText().toString().trim();
String _email = txtEmail.getText().toString().trim();
String _pass = txtPass.getText().toString().trim();
if(!TextUtils.isEmpty(_name) && !TextUtils.isEmpty(_email) && !TextUtils.isEmpty(_pass) ) {
mProgress.setMessage("Registrando ...");
mProgress.show();
firAuth.createUserWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
//the user has been registered
}
}
});
希望有所帮助