为 android 使用 firebase 验证 email/password
Authenticate email/password using firebase for android
我有一个非常基本的问题要问。我是 android 应用程序开发的新手。我严格按照来源的教程说明进行操作。但是当谈到存储用户数据时,我的导师使用 parse.com 。但 parse.com 明年将关闭,因此该选项已关闭。所以我决定改用 firebase,现在我安装了所有需要的包。 我想在 firebase 上为我的应用程序中的注册页面添加 email/password 身份验证。请向我提供我应该添加的代码,并指定它应该放置的位置(例如在 oncreate 下)
还有我应该初始化的东西
谢谢!
这是我来自 LoginActivity class 的代码,其中包括使用 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
}
}
});
希望对您有所帮助
我有一个非常基本的问题要问。我是 android 应用程序开发的新手。我严格按照来源的教程说明进行操作。但是当谈到存储用户数据时,我的导师使用 parse.com 。但 parse.com 明年将关闭,因此该选项已关闭。所以我决定改用 firebase,现在我安装了所有需要的包。 我想在 firebase 上为我的应用程序中的注册页面添加 email/password 身份验证。请向我提供我应该添加的代码,并指定它应该放置的位置(例如在 oncreate 下) 还有我应该初始化的东西
谢谢!
这是我来自 LoginActivity class 的代码,其中包括使用 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
}
}
});
希望对您有所帮助