按下按钮时无需任何理由即可调用onCreate()方法

时间:2019-12-04 11:16:08

标签: android firebase authentication firebase-authentication

在我的应用中,首先,我正在使用firebase的电话身份验证来验证电话号码。

我正在OTPVerificationActivity类中执行此过程。此类中的所有操作均正常,我也收到了OTP代码,并且用户已登录。

如果电话号码已通过验证,那么我正在通过发送验证电子邮件来验证电子邮件。我正在EmailVerificationActivity类中执行此过程。首先在此类中,我正在检查用户是否存在。如果用户在那里,那么我正在注销用户。

然后,我使用createUserWithEmailAndPassword函数创建帐户。之后,我想向用户发送验证电子邮件。

问题:-现在的问题是,创建帐户后,onCreate方法将再次被调用。因此,我无法发送验证电子邮件和其他任务。因此,如何阻止onCreate方法再次被调用。

  

注意:-   我尝试仅运行EmailVerificationActivity而不运行OTPVerificationActivity。   在那种情况下,所有事情都可以正常工作。我能够发送验证电子邮件,也能够验证用户。   但是当我同时使用OTPVerificationActivityEmailVerificationActivity时,我遇到了这个问题。   所以请帮助我解决这个问题。

public class OTPVerificationActivity extends AppCompatActivity {

String verificationID;

TextView messageTV;
EditText OTPET;

FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
       signInWithCredential(phoneAuthCredential);
    }

    @Override
    public void onVerificationFailed(@NonNull FirebaseException e) {

    }

    @Override
    public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
        super.onCodeSent(s, forceResendingToken);

        verificationID = s;
        Log.i("onSend",s);
    }
};

String phoneNumber;

public void sendVerificationCode(View view)
{
    String code = OTPET.getText().toString();
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationID,code);
    signInWithCredential(credential);
}

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

    messageTV = (TextView) findViewById(R.id.messageTextView);
    OTPET = (EditText) findViewById(R.id.OTPEditText);

    mAuth = FirebaseAuth.getInstance();
    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if(firebaseAuth.getCurrentUser() != null)
            {
                firebaseAuth.signOut();
                if(firebaseAuth.getCurrentUser() == null)
                {
                    Intent intent = new Intent(OTPVerificationActivity.this,EmailVerification.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                }
                else
                {
                    Log.i("firebaseAuth","user is not null");
                }
            }
        }
    };
    String message = "Please type the verification code sent to ";
    messageTV.setText(message+" " + "+91 " + getIntent().getStringExtra("phoneNumber"));
    phoneNumber = "+91" + getIntent().getStringExtra("phoneNumber");

    sendPhoneNumber(phoneNumber);
}

@Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthStateListener);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(mAuth.getCurrentUser() != null)
    {
        mAuth.signOut();
    }
}

public void sendPhoneNumber(String number)
{
    Log.i("sendPhoneNumber","inside it");
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            number,
            60,
            TimeUnit.SECONDS,
            TaskExecutors.MAIN_THREAD,
            mCallBack
    );
    Log.i("sendPhoneNumber","outside it");
}

private void signInWithCredential(final PhoneAuthCredential credential)
{
    mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(!task.isSuccessful())
            {
                Toast.makeText(OTPVerificationActivity.this, "Sign in Failed.", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(OTPVerificationActivity.this, "Phone number verified.", Toast.LENGTH_SHORT).show();
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.i("FailedListener",e.getMessage());
        }
    });
}

}

  

下面是EmailVerificationActivity类的代码。

public class EmailVerification extends AppCompatActivity {

EditText emailET, passwordET, confirmPasswordET;
AlertDialog.Builder builder;
AlertDialog alertDialog;
ProgressDialog progressDialog;

FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;

public void login(View view)
{
    startActivity(new Intent(EmailVerification.this,MainActivity.class));
}

public void submit(View view)
{
    String email = emailET.getText().toString();
    String password = passwordET.getText().toString();
    String confirmPassword = confirmPasswordET.getText().toString();

    if(!(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)))
    {
        if(password.equals(confirmPassword))
        {
            progressDialog.show();
            mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(task.isSuccessful())
                    {
                        //acount created...
                        mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                Log.i("verificationEmail","send");
                                progressDialog.dismiss();
                                if(!EmailVerification.this.isFinishing())
                                {
                                    alertDialog.show();
                                }
                                Toast.makeText(EmailVerification.this, "Email send successfully.", Toast.LENGTH_SHORT).show();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.i("verificationEmail","Not send");
                                //failed  to create account...
                                progressDialog.dismiss();
                                Toast.makeText(EmailVerification.this, "Failed to create account", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    else
                    {
                        //account not created...
                        progressDialog.dismiss();
                        Log.i("taskNotSuccessful",task.getException().getMessage());
                        Toast.makeText(EmailVerification.this, "Problem in creating account", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        else
        {
            Toast.makeText(this, "Confirm Password is not same as Password.", Toast.LENGTH_SHORT).show();
        }
    }
    else
    {
        Toast.makeText(this, "Fields are empty.", Toast.LENGTH_SHORT).show();
    }
}

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

    Log.i("onCreate","inside it");

    initializeWidgets();
    progressDialog = new ProgressDialog(EmailVerification.this);
    progressDialog.setMessage("Sending verification email.");

    builder= new AlertDialog.Builder(EmailVerification.this);
    builder.setTitle("Email Verification")
            .setMessage("We sent you a verification email, Please verify email before moving further.")
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(EmailVerification.this,SignInActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                }
            });

    alertDialog = builder.create();
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(R.style.MyProgressDialogStyle);
        }
    });

    mAuth = FirebaseAuth.getInstance();
    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if(firebaseAuth.getCurrentUser() != null)
            {
                // user is signed up...
                Log.i("mAuthStateChanged","user is not null.");
            }
            else
            {
                Log.i("mAuthStateChanged","user is null");
            }
        }
    };
}

@Override
protected void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthStateListener);
}

private void initializeWidgets()
{
    emailET = (EditText) findViewById(R.id.EmailEditText);
    passwordET = (EditText) findViewById(R.id.PasswordEditText);
    confirmPasswordET = (EditText) findViewById(R.id.ConfirmPasswordEditText);
}

}

1 个答案:

答案 0 :(得分:0)

oncreate

这是android的生命周期。如果您的活动由于释放内存,显式杀死等原因而被破坏,则会再次调用onCreate()。

当您切换活动时,活动通常不会被杀死。但在某些情况下可能会被杀死。因此,请将您的代码从onCreate()移到其他地方。

您无法控制android的生命周期。无论如何都会发生。因此,您需要服从他们