0

我在我的應用程序中集成了2種類型的註冊選項。一個帶有電子郵件和其他與Facebook。我已經成功整合了它們,但我無法知道用戶是否使用Facebook或電子郵件註冊,以便我可以相應地進行操作。如何知道用戶是否使用電子郵件或Facebook註冊?

這裏是我的代碼:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_sign_up); 

     userName = (EditText) findViewById(R.id.userName); 
     userEmail = (EditText) findViewById(R.id.userEmail); 
     userPassword = (EditText) findViewById(R.id.userPassword); 
     userPasswordAgain = (EditText) findViewById(R.id.userPasswordAgain); 
     signUpBtn = (AppCompatButton) findViewById(R.id.btnSignup); 
     coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); 
     progressDialog = new ProgressDialog(SignUpActivity.this); 

     FacebookSdk.sdkInitialize(getApplicationContext()); 
     AppEventsLogger.activateApp(this); 

     callbackManager = CallbackManager.Factory.create(); 
     LoginButton loginButton = (LoginButton) findViewById(R.id.login_button); 
     loginButton.setReadPermissions("email", "user_friends", "public_profile"); 
     loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
      @Override 
      public void onSuccess(LoginResult loginResult) { 
       Log.d("facebookLogin", "facebook:onSuccess:" + loginResult); 
       handleFacebookAccessToken(loginResult.getAccessToken()); 
      } 

      @Override 
      public void onCancel() { 
       Log.d("facebookLogin", "facebook:onCancel"); 
      } 

      @Override 
      public void onError(FacebookException error) { 
       Snackbar snackbar = Snackbar 
         .make(coordinatorLayout, error.getMessage(), Snackbar.LENGTH_SHORT); 
       snackbar.show(); 
      } 
     }); 

     mAuth = FirebaseAuth.getInstance(); 
     mDatabase = FirebaseDatabase.getInstance().getReference(); 

     loginLabel = (TextView) findViewById(R.id.loginLabel); 
     loginLabel.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent loginActivity = new Intent(SignUpActivity.this, LoginActivity.class); 
       startActivity(loginActivity); 
      } 
     }); 

     mAuthListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       FirebaseUser user = firebaseAuth.getCurrentUser(); 
       if (user != null) { 
        // User is signed in 
        Log.d("signedIn", "onAuthStateChanged:signed_in:" + user.getUid()); 
        mDatabase.child("users").child(user.getUid()).child("name").setValue(userName.getText().toString()); 
        mDatabase.child("users").child(user.getUid()).child("uniqueUserName").setValue(uniqueUserName.getText().toString()); 
        mDatabase.child("users").child(user.getUid()).child("followers").setValue("00"); 
        mDatabase.child("users").child(user.getUid()).child("following").setValue("00"); 
        mDatabase.child("unique-usernames").child(ts).setValue(uniqueUserName.getText().toString()); 
        Intent mainIntent = new Intent(SignUpActivity.this, SplashActivity.class); 
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
        startActivity(mainIntent); 
        progressDialog.dismiss(); 
       } else { 
        // User is signed out 
        Log.d("signedOut", "onAuthStateChanged:signed_out"); 
       } 
       // ... 
      } 
     }; 

     signUpBtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       if (isNetworkAvailable()) { 
        signUpUser(); 
       } else { 
        Snackbar snackbar = Snackbar 
          .make(coordinatorLayout, "No internet connection", Snackbar.LENGTH_SHORT); 
        snackbar.show(); 
       } 
      } 
     }); 


    } 

    public void signUpUser() { 
     if (userName.getText().toString().isEmpty()) { 
      Snackbar snackbar = Snackbar 
        .make(coordinatorLayout, "Name cannot be empty", Snackbar.LENGTH_SHORT); 
      snackbar.show(); 
     } else if (userEmail.getText().toString().isEmpty()) { 
      Snackbar snackbar = Snackbar 
        .make(coordinatorLayout, "Email cannot be empty", Snackbar.LENGTH_SHORT); 
      snackbar.show(); 
     } else if (userPassword.getText().toString().isEmpty()) { 
      Snackbar snackbar = Snackbar 
        .make(coordinatorLayout, "Password cannot be empty", Snackbar.LENGTH_SHORT); 
      snackbar.show(); 
     } else if (userPasswordAgain.getText().toString().isEmpty()) { 
      Snackbar snackbar = Snackbar 
        .make(coordinatorLayout, "Please re-type password", Snackbar.LENGTH_SHORT); 
      snackbar.show(); 
     } else if (!userPassword.getText().toString().equals(userPasswordAgain.getText().toString())) { 
      Snackbar snackbar = Snackbar 
        .make(coordinatorLayout, "Password do not match", Snackbar.LENGTH_SHORT); 
      snackbar.show(); 
     } else { 
      if (dialog == null) { 

       final AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this); 

       LayoutInflater inflater = this.getLayoutInflater(); 
       View alertDialogView = inflater.inflate(R.layout.choose_unique_name_dialog, null); 
       uniqueUserName = (EditText) alertDialogView.findViewById(R.id.uniqueUserName); 
       usernameChoosen = (TextView) alertDialogView.findViewById(R.id.usernameChoosen); 
       usernameWarning = (TextView) alertDialogView.findViewById(R.id.usernameWarning); 

       usernameChoosen.setVisibility(View.INVISIBLE); 
       usernameWarning.setVisibility(View.INVISIBLE); 

       builder.setTitle("Choose a unique username"); 
       builder.setView(alertDialogView); 
       builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialogInterface, int i) { 
         signingUpMethod(); 
        } 
       }); 
       dialog = builder.create(); 
      } 
      dialog.show(); 
      dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        wantToCloseDialog = false; 
        //Do stuff, possibly set wantToCloseDialog to true then... 
        if (uniqueUserName.getText().toString().isEmpty()) { 
//      Snackbar snackbar = Snackbar 
//        .make(coordinatorLayout, "Please choose a unique username", Snackbar.LENGTH_SHORT); 
//      snackbar.show(); 
         Toast.makeText(getBaseContext(), "Please choose a unique username", Toast.LENGTH_LONG).show(); 
         wantToCloseDialog = false; 
        } else { 

         mDatabase.child("unique-usernames").addValueEventListener(new ValueEventListener() { 
          @Override 
          public void onDataChange(DataSnapshot dataSnapshot) { 
           if (dataSnapshot.getValue() != null) { 
            if (dataSnapshot.getValue().toString().contains(uniqueUserName.getText().toString())) { 
             Toast.makeText(getBaseContext(), uniqueUserName.getText().toString() + " is already taken", Toast.LENGTH_LONG).show(); 
             usernameChoosen.setText(uniqueUserName.getText().toString()); 
             wantToCloseDialog = false; 
            } else { 
             signingUpMethod(); 
             wantToCloseDialog = true; 
            } 
           } else { 
            signingUpMethod(); 
            wantToCloseDialog = true; 
           } 
          } 

          @Override 
          public void onCancelled(DatabaseError databaseError) { 
           Snackbar snackbar = Snackbar 
             .make(coordinatorLayout, databaseError.getMessage(), Snackbar.LENGTH_LONG); 
           snackbar.show(); 
           wantToCloseDialog = false; 
          } 
         }); 
        } 
        if(wantToCloseDialog) 
         dialog.dismiss(); 
        //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false. 
       } 
      }); 
     } 
    } 

    public void signingUpMethod() { 
     progressDialog.setMessage("Signing up..."); 
     progressDialog.setCancelable(false); 
     progressDialog.show(); 
     mAuth.createUserWithEmailAndPassword(userEmail.getText().toString(), userPassword.getText().toString()) 
       .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
         Log.d("signUpSuccessful", "createUserWithEmail: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.d("exception", "onComplete: Failed=" + task.getException().getMessage()); 
          new AlertDialog.Builder(SignUpActivity.this) 
            .setMessage(task.getException().getMessage()) 
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 
             public void onClick(DialogInterface dialog, int which) { 
              // continue with delete 
             } 
            }) 
            .setIcon(android.R.drawable.ic_dialog_alert) 
            .show(); 
          progressDialog.dismiss(); 
         } 

         // ... 
        } 
       }); 
    } 

    private void handleFacebookAccessToken(AccessToken token) { 
     Log.d("token", "handleFacebookAccessToken:" + token); 

     AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); 
     mAuth.signInWithCredential(credential) 
       .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
         Log.d("facebookSignInSuccess", "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("facebookSignInFailed", "signInWithCredential", task.getException()); 
          Toast.makeText(SignUpActivity.this, "Authentication failed.", 
            Toast.LENGTH_SHORT).show(); 
         } 

         // ... 
        } 
       }); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     callbackManager.onActivityResult(requestCode, resultCode, data); 
    } 

在文檔here,它說,在第4點是

如果調用signInWithCredential成功,AuthStateListener運行onAuthStateChanged回調。在回調中,您可以使用getCurrentUser方法獲取用戶的帳戶數據。

AuthStateListener已經有電子郵件登錄代碼。

所以,我想知道,用什麼代碼,我可以知道,如果用戶已經註冊使用Facebook,以便我可以把相關的代碼在這個塊,如果他已經使用電子郵件註冊,我可以把相關的代碼。

請讓我知道。

+0

您可以遍歷提供者數據以找出用戶使用哪個提供者登錄。見http://stackoverflow.com/questions/38619628/how-to-determine-if-a-firebase-user-is-signed-in-using-facebook-authentication/38619970#38619970 –

+0

@FrankvanPuffelen是的,這是什麼我在尋找。我將使用此代碼並將迴應發生的事情。 –

回答

1

您可以將布爾當Facebook登錄被點擊時,isFacebookUser爲true,當簡單的登錄按鈕被點擊時isFacebookUser爲false。

檢查isFacebookUser布爾值哪裏有你需要的。就這樣!

您可以使用以下方法從Facebook SDK進行檢查。

public boolean isFacebookLoggedIn() { 
    return AccessToken.getCurrentAccessToken() != null; 
} 
+0

不存在任何方式來檢查我們正在註冊的提供商? –

+0

要添加到該答案,您甚至可以使用Facebook的sdk的Profile類來檢查用戶是否使用Facebook登錄。 'if(Profile profile!= null)然後返回false;' – eshb

+0

謝謝你的答案......你也可以幫忙:http://stackoverflow.com/questions/40661629/getting-e-androidruntime-error-reporting -crash-的Android-OS-transactiontoolargee –

0

只需檢查時,他立即登記u得到Facebook的帳號或沒有,如果你得到一個它的一個網站註冊否則你可以假設它是郵件註冊,你只有2個註冊此選項

+0

沒有辦法檢查我們正在註冊的提供商嗎? –

+0

im不知道它是如何在你使用的firebase體系結構中工作的,但簡單的方法是在註冊時設置字段,然後檢查響應中設置了哪個字段,當然如果正確實現只有一個字段將被設置。例如,我使用signIn = 1/2/3,根據註冊類型,然後使用此int值來知道在響應時間完成的註冊類型。但是,我建議您在嘗試此方法之前先閱讀Firebase文檔 – Ak9637

相關問題