Firebase Auth - Email login

直接輸入Email和密碼註冊登入

  • 1. 進入專案管理螢幕快照 2016-10-08 下午5.06.58
  • 2.進入Auth管理->登入方式->啟用電子郵件/密碼 螢幕快照 2016-10-08 下午5.09.09
  • 3.建立Android Project並且已經加入FireBase(不知道怎麼做可以參考FireBase-Android Start up)
  • 4.導入FireBase的Auth library
compile 'com.google.firebase:firebase-auth:9.6.1'
  • 5.然後開始寫登入流程的code

    取得FirebaseAuth這個最主要的物件,登入流程都會用到它

//取得FirebaseAuth 
private FirebaseAuth mAuth;

mAuth = FirebaseAuth.getInstance();
  • 6. 建立FirebaseAuth.AuthStateListener監聽Auth狀態變化
mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
          
        }
    };
      // ...
 @Override
public void onStart() {
    super.onStart();
    //可以在onStart時,加入FirebaseAuth.AuthStateListener
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    //可以在onStop時,移除FirebaseAuth.AuthStateListener
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

  • 7.第一次登入要先註冊帳號,使用FirebaseAuth的mAuth.createUserWithEmailAndPassword,直接給email, password兩個參數,然後在addOnCompleteListener接到完成的callback,可以透過回傳得task.isSuccessful()物件判斷登入是否成功,如果失敗可以用task.getException().toString()印出錯誤訊息來看原因.
mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(TAG, "createUserWithEmail:onComplete:" + 
                if (!task.isSuccessful()) {
                    Toast.makeText(EmailPasswordActivity.this,      R.string.auth_failed,
                            Toast.LENGTH_SHORT).show();
                }

                // ...
            }
        });

  • 8.已經註冊過了直接登入,使用FirebaseAuth的mAuth.signInWithEmailAndPassword,同上做法一樣
mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
             
                if (!task.isSuccessful()) {
                    Log.w(TAG, "signInWithEmail:failed", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, R.string.auth_failed,
                            Toast.LENGTH_SHORT).show();
                }

                // ...
            }
        });
  • 9. 可以透過mAuth.getCurrentUser()是否為 null,來判斷是否已經登入.
if(mAuth.getCurrentUser()==null){
    loginButton.setText("Login");
}else{
    loginButton.setText("Login out");
}
  • 10.登入會發現取得FirebaseUser的 displayName是null,可以用以下code去更新displayName,同時也可以設定一些使用者的個人設定,例如大頭貼...
 UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setDisplayName(nickName)
                .build();
        user.updateProfile(profileUpdates)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "User profile updated.");
                            finish();
                        }
                    }
                });

FireBase官方教學