Неполучающее базовое OTP-сообщение - PullRequest
0 голосов
/ 20 ноября 2018

Я новичок в разработке Android.Я не получаю OTP-сообщение от базы Fire, но если я ввожу код вручную, это сработает.Я не уверен, почему я не получаю текстовое сообщение.Ваша помощь высоко ценится.Я не уверен, правильно ли я делаю метод sendVerificationcode или нет.

Шаги выполнены: 1) Я добавил GSON-файл в каталог приложения. 2) Я добавил тестовый номер телефона в консоль FireBase. 3) Я добавил код SHA1 в базу данных. 4) Я добавил разрешение SMS в файл манифеста Android.5) Я включил проверку подлинности через Firebase в Android Studio. 6) Я тоже пробовал разные телефонные номера

VerifyPhoneActivity.java
public class VerifyPhoneActivity extends AppCompatActivity {


    private String verificationId;
    private FirebaseAuth mAuth;
    private ProgressBar progressBar;
    private EditText editText;

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

        mAuth = FirebaseAuth.getInstance();

        progressBar = findViewById(R.id.progressbar);
        editText = findViewById(R.id.editTextCode);

        String phonenumber = getIntent().getStringExtra("phonenumber");
        sendVerificationCode(phonenumber);

        findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String code = editText.getText().toString().trim();

                if (code.isEmpty() || code.length() < 6) {

                    editText.setError("Enter code...");
                    editText.requestFocus();
                    return;
                }
              verifyCode(code);
            }
        });

    }

   private void verifyCode(String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    signInWithCredential(credential);
 }



    private void signInWithCredential(PhoneAuthCredential credential) {
  // private void signInWithCredential(PhoneAuthCredential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {

                            Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                            startActivity(intent);

                        } else {
                            Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void sendVerificationCode(String number) {
        progressBar.setVisibility(View.VISIBLE);
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                number,
                60,
                TimeUnit.SECONDS,
                TaskExecutors.MAIN_THREAD,
                mCallBack
        );

    }

    private PhoneAuthProvider.OnVerificationStateChangedCallbacks
            mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

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

        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
            String code = phoneAuthCredential.getSmsCode();
            if (code != null) {
                editText.setText(code);
                verifyCode(code);
            }

            System.out.println("Hello Phone Number"+code);
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    };
}

Ниже код выглядит как неработающий:

@Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
    String code = phoneAuthCredential.getSmsCode();
   // String code="000000";
    if (code != null) {
        editText.setText(code);
        verifyCode(code);
    }

    System.out.println("Hello Phone Number2"+code);
}

1 Ответ

0 голосов
/ 21 ноября 2018

Используйте вот так:

onCreate

mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks()
        {

            @Override
            public void onVerificationCompleted(PhoneAuthCredential credential)
            {
                // This callback will be invoked in two situations:
                // 1 - Instant verification. In some cases the phone number can be instantly
                //     verified without needing to send or enter a verification code.
                // 2 - Auto-retrieval. On some devices Google Play services can automatically
                //     detect the incoming verification SMS and perform verificaiton without
                //     user action.
                Log.d(TAG, "onVerificationCompleted:" + credential);

                Log.e("number","credential=-=-=>>><<>>>signInWithPhoneAuthCredential-->>");
                signInWithPhoneAuthCredential(credential);

            }
            @Override
            public void onVerificationFailed(FirebaseException e)
            {
                // This callback is invoked in an invalid request for verification is made,
                // for instance if the the phone number format is not valid.
                Log.e(TAG, "onVerificationFailed", e);

                // Show a message and update the UI
                // ...
            }



            @Override
            public void onCodeSent(String verificationId,
                                   PhoneAuthProvider.ForceResendingToken token)
            {

                // The SMS verification code has been sent to the provided phone number, we
                // now need to ask the user to enter the code and then construct a credential
                // by combining the code with a verification ID.
                Log.e(TAG, "onCodeSent:" + verificationId+"<<token>>"+token);

                // Save verification ID and resending token so we can use them later
                mVerificationId = verificationId;

                //mResendToken = token;

                // ...
            }
        };

        //String phoneNumber=Settings.PREFIX + Settings.PREFIX_PHONE;

        String phoneNumber="your phone number with prefix";

        Log.e("number","credential=-=-=>>>22222>>"+phoneNumber);

        if(phoneNumber!=null && !phoneNumber.isEmpty())
        {
            startPhoneNumberVerification(phoneNumber);
        }

Метод:

private void startPhoneNumberVerification(String phoneNumber)
    {
        Log.e("startPhoneNumber","startPhoneNumberVerification------>>"+phoneNumber);
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks
        Log.e("startPhoneNumber","startPhoneNumberVerification--2222222---->>"+phoneNumber);
    }

Метод:

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential)
    {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
                {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task)
                    {
                        if (task.isSuccessful())
                        {
                            // Sign in success, update UI with the signed-in user's information
                            Log.e(TAG, "signInWithCredential:success");



                        } else
                            {
                            // Sign in failed, display a message and update the UI
                            Log.e(TAG, "signInWithCredential:failure", task.getException());
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException)
                            {

                            }
                        }
                    }
                });
    }
...